1

I was experimenting with numpy.uint() and numpy.around()

Here is what I have done:

>>> matrix = np.matrix([-32, -32.0, -3.91886975727153e-15])
>>> matrix
    matrix([[-3.20000000e+01, -3.20000000e+01, -3.91886976e-15]])
>>> np.uint(matrix)
...         
    matrix([[4294967264, 4294967264,          0]], dtype=uint32)
>>> np.around(matrix)
...                         
    matrix([[-32., -32.,  -0.]])
>>> np.uint(np.around(matrix))
...                         
    matrix([[4294967264, 4294967264,          0]], dtype=uint32)

Same happends with np.uint8 np.uint16 but with different values:

np.uint8(np.around(matrix))
matrix([[224, 224,   0]], dtype=uint8)

np.uint16(np.around(matrix))                        
matrix([[65504, 65504,     0]], dtype=uint16)

Why uint functions act that way?

Qwerth
  • 21
  • 6
  • 2
    '.... gives totally different results...': different from what? What did you expect? – Swifty Jul 21 '23 at 13:13
  • 2
    Do you know the meaning of `u` in `uint`? – Mechanic Pig Jul 21 '23 at 15:10
  • 1
    Converting negative values to **unsigned** integers currently cause an **undefined behaviour** in Numpy (though the value is often -1 converted to the target integer type that is typically `2**32-1` -- platform dependent). We tried as much as possible to add warning in this case but there are some rare cases where it is no message. Please check you use a recent version of Numpy and please be careful about warnings. We also assume users not to do conversion that does not make any sense (though they can happen when unexpected values are provided to such conversion functions). – Jérôme Richard Jul 21 '23 at 17:38
  • @Swifty , yes, from expected result. Now I understand the difference beetwen `int` and `uint` and why uint gives those results(which are actually predictable on my computer). @JérômeRichard , I am using numpy 1.24.1 version, If you mean Python warning, I didnt get any. – Qwerth Jul 22 '23 at 11:31
  • @Qwerth "undefined behaviour" is a common term it might be worth looking it up. it's worth figuring out what is defining the behaviour you see and whether you care about when that wouldn't apply. specifically here it's due to popular CPUs using [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) integer operations – Sam Mason Jul 22 '23 at 22:56

0 Answers0