Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 863
hatmatrix Avatar asked Oct 19 '11 17:10

hatmatrix


2 Answers

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.

like image 113
Fred Foo Avatar answered Nov 09 '22 14:11

Fred Foo


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.

like image 5
David Heffernan Avatar answered Nov 09 '22 16:11

David Heffernan