Splitting an integer sometimes gives incorrect casting results

What is the reason that these two divisions give different results? I am very confused, because with some numbers it gives the same results, and with some - not.

>>> import numpy as np
>>> a, b = np.array([844]), np.array([8186])
>>> a.dtype, b.dtype
(dtype('int32'), dtype('int32'))
>>> np.true_divide(a, b, dtype=np.float32)
array([ 0.10310286], dtype=float32)
>>> np.true_divide(a, b, dtype=np.float64)
array([-12.66666667]) # different result
>>> np.true_divide(a, b, dtype=np.float32).astype(np.float64)
array([ 0.10310286])

>>> a, b = np.array([1]), np.array([2])
>>> np.true_divide(a, b, dtype=np.float32)
array([ 0.5], dtype=float32)
>>> np.true_divide(a, b, dtype=np.float64)
array([ 0.5]) # same results

Tested on windows x64, python 3.5 and 3.6 x64, numpy 1.13.1.

+6
source share
1 answer

This is a numpy bug . Although this was presumably recorded in 2015, it looks like it is still causing problems.

When resolving a type signature, a failure due to a forced cast true_divideintroduces input into int8:

>>> np.int8(844) / np.int8(8186)
-12.666667

>>> np.true_divide(844, 8186, dtype=np.float64)
-12.666666666666666

-128 127, , int8.

:

>>> np.true_divide(844, 8186, signature='ii->d')  # int32, int32 -> float64
0.10310285853896897

>>> np.true_divide(844, 8186, signature=(np.int32, np.int32, np.float64))
0.10310285853896897
+1

All Articles