Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 numpy subtraction of two arrays
#1
Hi there

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?
Quote
#2
Firstly, you can directly subtract numpy arrays; no need for numpy.subtract.

Secondly, this is probably just a display issue. -2*10**-16 is basically zero with some added floating point imprecision.

Try adding this line before you print the array:
np.set_printoptions(suppress=True)
Not sure why you are getting this behavior by default though.

My results:
import numpy as np


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

b = np.ones((5,5), dtype=int)

print(b - a)
Output:
[[0. 0.14020837 1. 0.88233953 0.80646301] [0.1410302 0. 0.75888099 1. 1. ] [1. 0.75445877 0. 0.90765021 0.92874801] [0.68730018 0.77441286 0.70701599 0. 0.524457 ] [0.81119005 1. 0.93419183 0.67723179 0. ]]
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Numpy arrays and compatability with Fortran arrays merrittr 0 173 Sep-03-2019, 03:54 AM
Last Post: merrittr
  Converting set of tuples to set of 2D numpy arrays ThemePark 0 242 Aug-04-2019, 05:07 PM
Last Post: ThemePark
  numpy.copy / numpy.delete paul18fr 3 263 Jul-26-2019, 01:51 PM
Last Post: paul18fr
  "erlarge" a numpy-matrix to numpy-array PhysChem 2 406 Apr-09-2019, 04:54 PM
Last Post: PhysChem
  How to do matrix subtraction SriRajesh 0 883 Jun-01-2018, 02:00 PM
Last Post: SriRajesh

Forum Jump:


Users browsing this thread: 1 Guest(s)