python math,numpy模块不同的结果?
计算值的余弦时,我得到的结果略有不同。如何检查这种差异是否在机器精度范围内?
import math
math.cos(60.0/180.0*math.pi)
-> 0.5000000000000001
import numpy
numpy.cos(60.0/180.0*numpy.pi)
-> 0.50000000000000011
I get slightly different results calculating the cosine of a value. How can I check that this difference is within machine precision?
import math
math.cos(60.0/180.0*math.pi)
-> 0.5000000000000001
import numpy
numpy.cos(60.0/180.0*numpy.pi)
-> 0.50000000000000011
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
差异似乎仅由格式化例程引起:
请注意,
np.cos
返回np.float64
而不是float
,并且显然是该类型默认情况下打印方式不同。在常见硬件上,它们都实现为 64 位double
,因此精度上没有实际差异。The difference seems to be caused by the formatting routines only:
Note that
np.cos
returnsnp.float64
rather thanfloat
, and apparently that type is printed differently by default. On common hardware, they're both implemented as 64-bitdouble
, so there's no actual difference in precision.双精度算术可提供 15-16 位十进制有效数字的精度。这两个值与该精度一致。这里没什么好担心的。
请注意,我说“十进制”是为了与双精度值的二进制表示形式中用于有效数的 53 个“二进制”位进行对比。
Double precision arithmetic gives you precision of 15-16 decimal significant figures. These two values agree to that precision. Nothing worry about here.
Note that I say decimal to contrast with the 53 binary bits used for the significand in the binary representation of a double precision value.
尽管您的数字结果是相等的,但了解如何完全精确地检查它们仍然很有用。有几种方法可以做到这一点:
Eventhough your numbers turned out to be equal, it is still useful to know how to examine them at full precision. Here are a couple of ways to do it: