Python augmented assignment issue

后端 未结 4 791
挽巷
挽巷 2020-12-14 20:31

i ran into something interesting about the python augmented assignment +=

it seems to be automatic data type conversion is not always done for a +

4条回答
  •  萌比男神i
    2020-12-14 20:59

    If array is numpy.array (you don't actually specify), then the issue that's happening is because these arrays cannot change their type. When you create the array without a type specifier, it guesses a type. If you then attempt to do an operation that type doesn't support (like adding it to a type with a larger domain, like complex), numpy knows perform the calculation, but it also knows that the result can only be stored in the type with the larger domain. It complains (on my machine, anyway, the first time I do such an assignment) that the result doesn't fit. When you do a regular addition, a new array has to be made in any case, and numpy gives it the correct type.

    >>> a=numpy.array([1])
    >>> a.dtype
    dtype('int32')
    >>> b=numpy.array([1+1j])
    >>> b.dtype
    dtype('complex128')
    >>> a+b
    array([ 2.+1.j])
    >>> (a+b).dtype
    dtype('complex128')
    >>> a+=b
    >>> a
    array([2])
    >>> a.dtype
    dtype('int32')
    >>> 
    

提交回复
热议问题