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?

1
  • 1
    A little unrelated note: the first row (or column) is with index 0 and not 1 Commented Jul 13, 2016 at 13:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.