计算圆周率pi的代码

计算至小数点后1000位:

#include <stdio.h>
long a = 10000, b = 0, c = 2800, d, e, f[2801], g;
void main()
{
	for (; b - c;)
		f[b++] = a / 5;
	for (; d = 0, g = c * 2; c -= 14, printf("%04d", e + d / a), e = d % a)
		for (b = c; d += f[b] * a, f[b] = d % --g, d /= g--, --b; d *= b);
}

31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067982148086513282306647093844609550582231725359408128481117450
28410270193852110555964462294895493038196442881097566593344612847564823378678316
52712019091456485669234603486104543266482133936072602491412737245870066063155881
74881520920962829254091715364367892590360011330530548820466521384146951941511609
43305727036575959195309218611738193261179310511854807446237996274956735188575272
48912279381830119491298336733624406566430860213949463952247371907021798609437027
70539217176293176752384674818467669405132000568127145263560827785771342757789609
17363717872146844090122495343014654958537105079227968925892354201995611212902196
08640344181598136297747713099605187072113499999983729780499510597317328160963185

//

#include <stdio.h>
int main()
{
	double a[100];
	double pi[100];
	int i;
	a[1] = 0.5;
	for (i = 1; i < 99; ++i) {
		a[i + 1] = sqrt(a[i]) / 2 + 0.5;
	}
	pi[0] = 0;
	for (i = 1; i < 100; ++i) {
		pi[i] = sqrt(1 - a[i])*pow(2, i + 1);
		if (pi[i] <= pi[i - 1]) {
			break;
		}
		printf("%d: %.15lf\n", i, pi[i]);
	}
	return 0;
}

1: 2.828427124746190
2: 3.061467458920719
3: 3.121445152258053
4: 3.136548490545941
5: 3.140331156954739
6: 3.141277250932757
7: 3.141513801144725
8: 3.141572940365567
9: 3.141587725279961
10: 3.141591421504635
11: 3.141592345611077
12: 3.141592576545004
13: 3.141592635834842
14: 3.141592645321215

//
Python,小数点后498位;

from decimal import Decimal as D
from decimal import getcontext
getcontext().prec = 1000
a = [D(1.0)] * 1000
pi = [D(1.0)] * 1000
a[1] = D(0.5)
for i in range(1,999):
    a[i+1] = a[i].sqrt() / 2 + D(0.5)
pi[0] = D(0.0)
for i in range(1,1000):
    pi[i] = (1-a[i]).sqrt() * (2 ** (i+1))
    if pi[i] < pi[i-1]:
        break
    print(i, pi[i])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值