Python pi calculation?

前端 未结 3 1889
失恋的感觉
失恋的感觉 2020-12-01 12:49

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:

3条回答
  •  余生分开走
    2020-12-01 13:25

    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))
    

提交回复
热议问题