简体   繁体   中英

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. On common hardware, they're both implemented as 64-bit double , so there's no actual difference in precision.

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:

>>> 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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