4

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?

user2979409
  • 773
  • 1
  • 12
  • 23

1 Answers1

2

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

Community
  • 1
  • 1
Peter Wang
  • 1,808
  • 1
  • 11
  • 28
  • 2
    Likely this is the reason; for completeness it should be mentioned that the sum of floating point numbers depends on the order of summation, and the summation of matrix-rows or matrix-columns may happen to be in different order (one'd have to look at the source code to be sure). –  Jul 13 '16 at 13:38