Reputation: 341
I am having a problem with series calculations in python where they all fail after the 15th digit. I am using Canopy.
For example
3.1415926535897932384626433832795028841971693993751 Actual pi 3.14159265358979444826559301873203366994857788085938 My result 3.1415926535897932384626433832795028841971XXXXXXXXXX The question
The equation 16arctan(1/5) - 4arctan(1/239):
# For Machin
mm = 0.
totalm1 = 0.
while mm <= 100:
machin1 = (16.)*(-1)**(mm)*((1./5)**(1+2.*mm))/(2.*mm+1) -(4.)*(-1)**(mm)*((1./239)**(1+2.*mm))/(2.*mm+1)
totalm1 += machin1
mm += 1
print "%50.50f" %totalm1
How to solve this?
Upvotes: 2
Views: 286
Reputation: 280554
Floating-point numbers only have about 15 digits of precision. If you need more significant digits, use an arbitrary-precision math library. The built-in decimal
module may be suitable, or you could try mpmath
, which seems to have a lot more features.
An example of computing the square root of 2 with the decimal
module:
>>> import decimal
>>> decimal.getcontext().prec = 50 # Compute with 50 digits of precision
>>> decimal.Decimal('2') ** decimal.Decimal('0.5')
Decimal('1.4142135623730950488016887242096980785696718753769')
Upvotes: 2