Prevent rounding to zero in Python

I have a program designed to approximate pi using the Chudnovsky algorithm, but the term in my equation, which is very small, is rounded to zero.

Here is the algorithm:

import math
from decimal import *
getcontext().prec = 100

pi = Decimal(0.0)
C = Decimal(12/(math.sqrt(640320**3)))
k = 0
x = Decimal(0.0)
result = Decimal(0.0)
sign = 1
while k<10:
    r = Decimal(math.factorial(6*k)/((math.factorial(k)**3)*math.factorial(3*k)))
    s = Decimal((13591409+545140134*k)/((640320**3)**k))
    x += Decimal(sign*r*s)
    sign = sign*(-1)
    k += 1
result = Decimal(C*x)
pi = Decimal(1/result)


print Decimal(pi)

Equations can be sharper without “decimal” terms.

import math

pi = 0.0
C = 12/(math.sqrt(640320**3))
k = 0
x = 0.0
result = 0.0
sign = 1
while k<10:
    r = math.factorial(6*k)/((math.factorial(k)**3)*math.factorial(3*k))
    s = (13591409+545140134*k)/((640320**3)**k)
    x += sign*r*s
    sign = sign*(-1)
    k += 1
result = C*x
pi = 1/result

print pi

The problem is with the s variable. For k> 0, it always comes to zero. for example, for k = 1, s should be approximately 2.1e-9, but instead it is zero. Because of this, all my terms after the first = 0. How do I get python to calculate the exact value of s instead of rounding to 0?

+5
source share
4 answers

Try:

s = Decimal((13591409+545140134*k)) / Decimal(((640320**3)**k))

, , - python - Decimal , .

, r.

+3

Python 2.x, , , :

from __future__ import division

, , , ( ) . x / y int, x y int s, .

, , , Python, , , .

Python 3 , , , - Python 2. __future__. , - ( , ). , , , , .

+2

.

Python 2.x, / . , .

math.sqrt() 16 . C ~ 16 , 16 .

+1

I feel that the problem with 's' is that all members are integers, so you do integer math calculations. A very simple workaround is to use 3.0in the denominator. Only one float is required to receive a returned float.

0
source

All Articles