jrjames83
jrjames83

Reputation: 901

Numpy 1d array subtraction - not getting expected result.

I have 2 arrays of shape (128,). I want the elementwise difference between them.

for idx, x in enumerate(test):
    if idx == 0:
        print (test[idx])
        print()
        print(library[idx])
        print()
        print(np.abs(np.subtract(library[idx],test[idx])))

output:

[186   3 172  80 187 120 127 172  96 213 103 107 137 119  33  53  54 113
 200  78 140 234  77  94 151  64 199 218 170  73 152  73   0   5 121  42
   0 106 166  80 115 220  56  66 194 187  51 132  55  73 150  83  91 204
 108  58 183   0  32 240 255  55 151 255 189 153  77  89  42 176 204 170
  93 117 194 195  59 204 149  55 111 255 218  48  72 171 122 163 255 155
 198 179  69 173 108   0   0 176 249 214 193 255 106 116   0  47 255 255
 255 255 210 175  67   0  95 120  21 158   0  72 120 255 121 208 255   0
  61 255]

[189   0 178  72 177 124 123 167  81 235 110 123 139 107  39  54  34 102
 195  59 156 255  66 112 161  65 180 236 181  69 142  82   0   0 152  38
   0 102 146  86 117 230  59  77 220 182  44 121  63  59 146  41  92 213
 146  70 184   0   0 255 255  42 165 255 245 152 114  88  63 138 255 158
  96 141 221 201  47 191 179  42 156 255 237   7 136 168 133 142 254 164
 236 250  56 202 141   0   0 197 255 184 212 255 108 133   0   7 255 255
 255 255 243 197  74   0  50 143  24 175   0  74 101 255 121 207 255   0
 146 255]

[  3 253   6 248 246   4 252 251 241  22   7  16   2 244   6   1 236 245
 251 237  16  21 245  18  10   1 237  18  11 252 246   9   0 251  31 252
   0 252 236   6   2  10   3  11  26 251 249 245   8 242 252 214   1   9
  38  12   1   0 224  15   0 243  14   0  56 255  37 255  21 218  51 244
   3  24  27   6 244 243  30 243  45   0  19 215  64 253  11 235 255   9
  38  71 243  29  33   0   0  21   6 226  19   0   2  17   0 216   0   0
   0   0  33  22   7   0 211  23   3  17   0   2 237   0   0 255   0   0
  85   0]

So it reads, the last array printed out is the difference between the first two arrays.

189 - 186 is 3 3 - 0 is 3 (not 253)

I must be missing something trivial.

I'd rather not zip and subtract the values as I have a ton of data.

Upvotes: 0

Views: 45

Answers (2)

user2357112
user2357112

Reputation: 281843

Your arrays probably have dtype uint8; they cannot hold values outside the interval [0, 256), and subtracting 3 from 0 wraps around to 253. The absolute value of 253 is still 253.

Use a different dtype, or restructure your computation to avoid hitting the limits of the dtype you're using.

Upvotes: 2

Yilun Zhang
Yilun Zhang

Reputation: 9018

You can just simply subtract two numpy arrays like this, it is element-wise operation:

>test = np.array([1,2,3])
>library = np.array([1,1,1])
>np.abs(library - test)
array([0, 1, 2])

Upvotes: 0

Related Questions