python计算圆周率,Python的圆周率计算?

I am a python beginner and I want to calculate pi. I tried using the Chudnovsky algorithm because I heard that it is faster than other algorithms.

This is my code:

from math import factorial

from decimal import Decimal, getcontext

getcontext().prec=100

def calc(n):

t= Decimal(0)

pi = Decimal(0)

deno= Decimal(0)

k = 0

for k in range(n):

t = ((-1)**k)*(factorial(6*k))*(13591409+545140134*k)

deno = factorial(3*k)*(factorial(k)**3)*(640320**(3*k))

pi += Decimal(t)/Decimal(deno)

pi = pi * Decimal(12)/Decimal(640320**(1.5))

pi = 1/pi

return pi

print calc(25)

For some reason this code yields the vakue of pi up to only 15 decimals as compared with the acceptable value. I tried to solve this by increasing the precision value; this increases the number of digits, but only the first 15 are still accurate. I tried changing the way it calculates the algorithm and it didn't work either. So my question is, is there something that can be done to this code to make it much more accurate or would I have to use another algorithm? I would appreciate help with this because I don't know how to operate with so many digits in python. I would like to be able to control the number of (correct) digits determined and displayed by the program -- whether 10, 100, 1000, etc.

解决方案

It seems you are losing precision in this line:

pi = pi * Decimal(12)/Decimal(640320**(1.5))

Try using:

pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))

This happens because even though Python can handle arbitrary scale integers, it doesn't do so well with floats.

Bonus

A single line implementation using another algorithm (the BBP formula):

from decimal import Decimal, getcontext

getcontext().prec=100

print sum(1/Decimal(16)**k *

(Decimal(4)/(8*k+1) -

Decimal(2)/(8*k+4) -

Decimal(1)/(8*k+5) -

Decimal(1)/(8*k+6)) for k in range(100))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值