Skip to main content
added 71 characters in body
Source Link
jolvi
  • 4.7k
  • 2
  • 17
  • 13

A surprise with the *= assignment in combination with numpy.array:

>>> from numpy import array >>> a = array([1, 2, 3]) >>> a *= 1.1 >>> print(a) [1 2 3] # not quite what we expect or would like to see >>> print(a.dtype) int64 # and this is why >>> a = 1.1 * a # here, a new array is created >>> print(a, a.dtype) [ 1.1 2.2 3.3] float64 # with the expected outcome 

Surprising, annoying, but understandable. The *= operator will not change the type of the array data, thereby multiplication of an int array by a float will fail in the conventional meaning of this multiplication. The Python version a = 1; a *= 1.1 in the other hand works as expected.

A surprise with the *= assignment in combination with numpy.array:

>>> from numpy import array >>> a = array([1, 2, 3]) >>> a *= 1.1 >>> print(a) [1 2 3] # not quite what we expect or would like to see >>> print(a.dtype) int64 # and this is why >>> a = 1.1 * a # here, a new array is created >>> print(a, a.dtype) [ 1.1 2.2 3.3] float64 # with the expected outcome 

Surprising, annoying, but understandable. The *= operator will not change the type of the array data, thereby multiplication of an int array by a float will fail in the conventional meaning of this multiplication.

A surprise with the *= assignment in combination with numpy.array:

>>> from numpy import array >>> a = array([1, 2, 3]) >>> a *= 1.1 >>> print(a) [1 2 3] # not quite what we expect or would like to see >>> print(a.dtype) int64 # and this is why >>> a = 1.1 * a # here, a new array is created >>> print(a, a.dtype) [ 1.1 2.2 3.3] float64 # with the expected outcome 

Surprising, annoying, but understandable. The *= operator will not change the type of the array data, thereby multiplication of an int array by a float will fail in the conventional meaning of this multiplication. The Python version a = 1; a *= 1.1 in the other hand works as expected.

Source Link
jolvi
  • 4.7k
  • 2
  • 17
  • 13

A surprise with the *= assignment in combination with numpy.array:

>>> from numpy import array >>> a = array([1, 2, 3]) >>> a *= 1.1 >>> print(a) [1 2 3] # not quite what we expect or would like to see >>> print(a.dtype) int64 # and this is why >>> a = 1.1 * a # here, a new array is created >>> print(a, a.dtype) [ 1.1 2.2 3.3] float64 # with the expected outcome 

Surprising, annoying, but understandable. The *= operator will not change the type of the array data, thereby multiplication of an int array by a float will fail in the conventional meaning of this multiplication.