Cython的计算不正确 [英] Cython's calculations are incorrect
问题描述
我实现了Madhava–Leibniz系列,先用Python计算pi,然后在Cython中提高速度。 Python版本:
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The 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版本:
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)
当我停止Python版本时,它已正确计算出pi为3.141592 。 Cython版本最终以3.141597结尾,出现了我不记得的更多数字(我的终端崩溃了),但是不正确。为什么Cython版本的计算不正确?
When I stopped the Python version it had correctly calculated pi to 3.141592. The Cython version eventually ended up at 3.141597 with some more digits that I don't remember (my terminal crashed) but were incorrect. Why are the Cython version's calculations incorrect?
推荐答案
您正在使用 float
在Cython版本中-这是单精度!使用 double
代替,它对应于Python的 float
(很有趣)。 C类型 float
仅具有约8个有效十进制数字,而 double
或Python的 float
大约有16位数字。
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.
这篇关于Cython的计算不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!