[Numpy-discussion] inconsistent dtype promotion in dimensionless arrays

Robert Kern robert.kern@gmail....
Thu Apr 5 17:07:29 CDT 2007


Matthew Koichi Grimes wrote:
> I've noticed two dtype promotion behaviors that are surprising to me. 
> I'm hoping to get people's input as to whether I should file bug tickets 
> on them.
> 
> First weirdness:
> When you do an operation between a float32 Numpy array and a python or 
> Numpy float64, the result is a float32 array, not a float64 array:
> 
>  >>> import numpy as N
>  >>> vec32 = N.ones(2, N.float32)
>  >>> vec32
> array([ 1.,  1.], dtype=float32)
>  >>> result = vec32 - 1.0
>  >>> result.dtype
> dtype('float32')
>  >>> result = vec32 - N.float64(1.0)
>  >>> result.dtype
> dtype('float32')
> 
> 
> This is of course not the case if the float64 is replaced with a 
> 1-dimensional numpy array:
>  >>> result = vec32 - N.array([1.0], N.float64)
>  >>> result.dtype
> dtype('float64')

This is actually expected behavior. The rule is that when an array is operated
with a scalar and the dtypes are of the same kind (floating point, integer,
complex are all different "kinds"; float32 and float64 are of the same kind,
float32 and int32 are not), then the array's dtype takes precedence. This helps
resolve long-standing issues of using float32 arrays and still multiplying them
by 2.0, for example. When the two are of different kinds (float32 and int32, for
example), the common "safe" dtype is negotiated between the two.

> Second weirdness:
> Type promotion doesn't happen if you replace the 1-d, 1-element array 
> with a 0-d array:
> 
>  >>> result = vec32 - N.array(1.0, N.float64)
>  >>> result.dtype
> dtype('float32')
> 
> 
> The second weirdness in particular strikes me as inconsistent when 
> compared to operations between vec32 and the 1-d array.

Rank-0 arrays are treated as scalars in ufuncs, too, so these are consistent.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco


More information about the Numpy-discussion mailing list