Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Pi with decimal on Python

Tags:

python

pi

I'm trying to calculate pi with arbitrary precision on Python using one of Ramanujan's formulas: http://en.wikipedia.org/wiki/Approximations_of_%CF%80#20th_century. It basically requires lots of factorials and high-precision floating numbers division.

Here's my code so far: http://pastie.org/private/pa6ijmoowiwiw4xwiqmq

I'm getting error somewhere around the fifteenth digit of pi( 3.1415926535897930 and it should be 3.1415926535897932 ). Can you give some advice why is it happening? I' am using decimal type and the docs say that it allows arbitrary precision floating and integer numbers.

PS: It's a homework assignment so i can't use another formula. PSS: I'm using python 2.7

Thanks:)

like image 280
GeneralFailure Avatar asked Jun 03 '13 07:06

GeneralFailure


People also ask

How do you find pi with decimals?

There are essentially 3 different methods to calculate pi to many decimals. One of the oldest is to use the power series expansion of atan(x) = x - x^3/3 + x^5/5 - ... together with formulas like pi = 16*atan(1/5) - 4*atan(1/239). This gives about 1.4 decimals per term.

Can you put pi in Python?

The pi (π ) is a constant of the math library in Python that returns the value 3.141592653589793. Pi helps calculate the area and circumference of the circle or other mathematical figures.

How do you find pi with n digits?

Pi = SUMk=0 to infinity 16-k [ 4/(8k+1) – 2/(8k+4) – 1/(8k+5) – 1/(8k+6) ]. The reason this pi formula is so interesting is because it can be used to calculate the N-th digit of Pi (in base 16) without having to calculate all of the previous digits!


1 Answers

Use Decimal(2).sqrt() instead of Decimal(sqrt(2)).

I've checked the first 1000 digits and it seems to work fine. By the way, for some reason your code outputs 1007 decimal places instead of 1000.

like image 105
kirelagin Avatar answered Oct 18 '22 03:10

kirelagin