Keaton's calculations are incorrect

I implemented the Madhava-Leibniz series to calculate pi in Python and then in Cython to improve speed. Python version:

from __future__ import division pi = 0 l = 1 x = True while True: if x: pi += 4/l else: pi -= 4/l x = not x l += 2 print str(pi) 

Cython Version:

 cdef float pi = 0.0 cdef float l = 1.0 cdef unsigned short x = True while True: if x: pi += 4.0/l else: pi -= 4.0/l x = not x l += 2 print str(pi) 

When I stopped the Python version, it correctly calculated pi to 3.141592. The Cython version ended up at 3.141597 with a few more numbers that I don’t remember (my terminal crashed) but were incorrect. Why are Cython version errors incorrect?

+7
source share
3 answers

You are using float in the version of Cython - single precision ! Use double instead, which corresponds to a Python float (oddly enough). Type C float contains about 8 significant decimal digits, while double or Python float have about 16 digits.

+18
source

If you want to increase the speed, note that you can simplify the logic by unrolling the loop once, for example:

 cdef double pi = 0.0 cdef double L = 1.0 while True: pi += 4.0/L - 4.0/(L+2.0) L += 4.0 print str(pi) 

Also note that you do not need to invoke printing inside the loop - it probably takes ten times longer than the rest of the calculations.

0
source

How do you know when you're done? Do you think that the value for pi will fluctuate relative to the true value, and you expect that if you stop the code at some point, you can have a value that is too high (or too low)?

-one
source

All Articles