Home > Software design >  Why does python throw a "true_divide" TypeError when using "/=" assignment on Nu
Why does python throw a "true_divide" TypeError when using "/=" assignment on Nu

Time:11-17

I get TypeError when using /= on a NumPy array right after creation:

>>> arr = np.array([1,2,3])
>>> arr /= 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-ff91ab204368> in <module>
----> 1 arr /= 2

TypeError: No loop matching the specified signature and casting
was found for ufunc true_divide

But I can do:

>>> arr = arr / 2
>>> arr
array([0.5, 1, 1.5])

What's weirder, is that after doing the above I can do:

>>> arr /= 2
>>> arr
array([0.25, 0.5, 0.75])

What is happening?

CodePudding user response:

I believe it is because your array is an integer array. When you do /=, it tries to do floor division and put the values in-place back into the original array, but it can't because the new values are floats and the array has an integer dtype. But when you use /, it makes a new array with a float dtype, which you then assign to the original name, and this float array supports /=.

CodePudding user response:

The answer is that ([1, 2, 3]) is type int64 and if their is a float in the array than the type is float64. If you want to know which type your array is therefore you can use the '.dtype'. You can define this int64 array to a float64 array.

CodePudding user response:

As other answer already mentioned issue is due to dtype. Let's go through the code and try to understand the issue.
NOTE: id() gives unique identify of object
When you created the array

>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> id(arr) # Hash address of array
139866867761280
>>> arr.dtype # dtype of array
dtype('int64')

As you can see type of array is int64. When you try to divide it by 2 it tried to write it back in same ndarray which is of type int64 where as result is float64 and hence the error

>>> arr /= 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: No loop matching the specified signature and casting was found for ufunc true_divide

Now when you do

>>> arr = arr / 2
>>> id(arr)
139866844116592
>>> arr.dtype
dtype('float64')

Notice How address is changes from previous operation and type is changed. Because address is changed and new ndarray is created hence no error.
Now when you try arr /= 2

>>> arr /= 2
>>> arr
array([0.25, 0.5 , 0.75])
>>> arr.dtype
dtype('float64')
>>> id(arr)
139866844116592

Cause dtype was already float64 we were able to perform the operation. Notice how the address remains the same. it's in place operation.

  • Related