user2979409
user2979409

Reputation: 791

Inconsistent result with Python numpy matrix

I have a matrix with float values and I try to get the summary of columns and rows. This matrix is symmetric.

>>> np.sum(n2[1,:]) #summing second row
0.80822400592582844
>>> np.sum(n2[:,1]) #summing second col
0.80822400592582844
>>> np.sum(n2, axis=0)[1]
0.80822400592582899
>>> np.sum(n2, axis=1)[1]
0.80822400592582844

It gives different results. Why?

Upvotes: 4

Views: 213

Answers (1)

Peter Wang
Peter Wang

Reputation: 1838

The numbers numpy uses are doubles, with accuracy up to 16 decimal places. It looks like the differences happen at the 16th place, with the rest of the digits being equal. If you don't need this accuracy, you could use the rounding function np.around(), or you could actually try using the np.longdouble type to get a higher degree of accuracy.

You can check the accuracy of the types using np.finfo:

>>> print np.finfo(np.double).precision
>>> 15

Some numpy functions won't accept long doubles I believe, and will cast it down to a double, truncating the extra digits. Numpy precision

Upvotes: 2

Related Questions