Cython's calculations are incorrect

↘锁芯ラ 提交于 2019-12-04 04:52:22

You are using float in the Cython version -- that's single precision! Use double instead, which corresponds to Python's float (funnily enough). The C type float only has about 8 significant decimal digits, whereas double or Python's float have about 16 digits.

If you want to increase speed, note that you can simplify the logic by unrolling your loop once, like so:

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 don't have to call print inside the loop - it is probably taking ten times longer than the rest of the calculation.

How do you know when it's finished? Have you considered that the value for pi would oscillate about the true value, and you would expect that if you stopped the code at some point, you could have a value that is too high (or too low)?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!