0

So I want to subtract two numpy arrays a and b:

a=[[ 1. 0.85979163 0. 0.11766047 0.19353699]
[ 0.8589698 1. 0.24111901 0. 0. ]
[ 0. 0.24554123 1. 0.09234979 0.07125199]
[ 0.31269982 0.22558714 0.29298401 1. 0.475543 ]
[ 0.18880995 0. 0.06580817 0.32276821 1. ]]


b=[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]

When I use the following command:

y=numpy.subtract(b,a)

I get an output array:

y= [[ -2.22044605e-16 1.40208370e-01 1.00000000e+00 8.82339528e-01
8.06463005e-01]
[ 1.41030195e-01 0.00000000e+00 7.58880995e-01 1.00000000e+00
1.00000000e+00]
[ 1.00000000e+00 7.54458767e-01 -2.22044605e-16 9.07650211e-01
9.28748013e-01]
[ 6.87300178e-01 7.74412855e-01 7.07015986e-01 0.00000000e+00
5.24457002e-01]
[ 8.11190053e-01 1.00000000e+00 9.34191829e-01 6.77231787e-01
0.00000000e+00]]

And it's really confusing me as to how it's outputting these values.

When I tried to troubleshoot and do:

y=b[0,0]-a[0,0]

I got y=0.. which makes sense because i would be subtracting 1-1. But in the output array I'm getting a value of -2.22044605e-16 instead.

Do you have any idea as to why this might be happening and what I can do to fix it?

3
  • I cannot reproduce your error with the data that you provided (I get all 0s on the main diagonal). I hypothesize that a is not exactly as you describe it. Perhaps it is a result of another computation, and 1.0 is not exactly 1.0. Commented Sep 24, 2018 at 1:04
  • There is no "fixing it" it is the nature of representing numbers in a computer. See en.wikipedia.org/wiki/Floating-point_arithmetic Commented Sep 24, 2018 at 1:12
  • Possible duplicate of how set numpy floating point accuracy? Commented Sep 24, 2018 at 1:13

1 Answer 1

2

e-16 is essentially 0. You typically can't avoid numerical precision errors when dealing with floats. But you can always chop the tiny values to 0 exactly afterwards if that's important to you. Note that you probably see 1. when printing a only because numpy doesn't show the full precision by default when printing an array. Try print(a[0,0]) and you'll probably see something like 1.00000000005. For example try printing np.array([1.000000001]) and np.array([1.000000001])-1, and np.array([1.000000001])[0]...

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

Comments

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.