0

If you add a number to an array slot that takes it outside of it's datatype range, it will loop around past the range and back to zero. Example with uint8, whose max range is 255:

z = np.zeros(2, dtype=np.uint8)

z[0]=z[0]+267

print(z[0])

> 11

I would like to prevent any addition which makes the slot loop back to zero.

I came up with this function

def ifAdd( addCand, numb):
    if addCand+numb >255:
        return
    else:
        addCand = addCand + numb

ifAdd(z[0], 267)

I am wondering if there is a more pythonic of numpthonic way of doing this. Or at the least, a more computationally more efficient method.

SantoshGupta7
  • 5,607
  • 14
  • 58
  • 116

1 Answers1

-1

What about lambda?

In [15]: z = np.zeros(2, dtype=np.uint8)                                        

In [16]: f = lambda x, y: x if x+y > 255 else x+y                               

In [17]: z[0] = f(z[0], 267)                                                    

In [18]: z                                                                      
Out[18]: array([0, 0], dtype=uint8)

In [19]: z[0] = f(z[0], 1)                                                      

In [20]: z                                                                      
Out[20]: array([1, 0], dtype=uint8)

trsvchn
  • 8,033
  • 3
  • 23
  • 30