简体   繁体   English

python数学,numpy模块不同的结果?

[英]python math, numpy modules different results?

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

The difference seems to be caused by the formatting routines only: 差异似乎只是由格式化例程引起的:

>>> '%.30f' % math.cos(60./180.*math.pi)
'0.500000000000000111022302462516'
>>> '%.30f' % np.cos(60./180.*np.pi)
'0.500000000000000111022302462516'

Note that np.cos returns np.float64 rather than float , and apparently that type is printed differently by default. 请注意, np.cos返回np.float64而不是float ,显然默认情况下该类型的打印方式不同。 On common hardware, they're both implemented as 64-bit double , so there's no actual difference in precision. 在通用硬件上,它们都实现为64位double精度,因此精度没有实际差异。

Double precision arithmetic gives you precision of 15-16 decimal significant figures. 双精度算术为您提供15-16十进制有效数字的精度。 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. 注意,我说十进制与用于双精度值的二进制表示中的有效的53个二进制位形成对比。

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: 以下是几种方法:

>>> a = 1.1 + 2.2
>>> b = 3.3
>>> a == b
False
>>> from decimal import Decimal
>>> Decimal.from_float(a)
Decimal('3.300000000000000266453525910037569701671600341796875')
>>> Decimal.from_float(b)
Decimal('3.29999999999999982236431605997495353221893310546875')
>>> a.hex()
'0x1.a666666666667p+1'
>>> b.hex()
'0x1.a666666666666p+1'
>>> a.as_integer_ratio()
(7430939385161319, 2251799813685248)
>>> b.as_integer_ratio()
(3715469692580659, 1125899906842624)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM