numpy subtraction of two arrays - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: numpy subtraction of two arrays (/thread-13014.html) |
numpy subtraction of two arrays - devenuro - Sep-24-2018 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? RE: numpy subtraction of two arrays - Mekire - Sep-24-2018 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)
|