Hi all, I'd like to set the data type for what numpy.where creates. For example: import numpy as N N.where(a >= 5, 5, 0) creates an integer array, which makes sense. N.where(a >= 5, 5.0, 0) creates a float64 array, which also makes sense, but I'd like a float32 array, so I tried: N.where(a >= 5, array(5.0, dtype=N.float32), 0) but I got a float64 array again. How can I get a float32 array? where doesn't take a dtype argument -- maybe it should? numpy version 1.0 thanks, -Chris
Chris Barker wrote:
Hi all,
I'd like to set the data type for what numpy.where creates. For example:
import numpy as N
N.where(a >= 5, 5, 0)
creates an integer array, which makes sense.
N.where(a >= 5, 5.0, 0)
creates a float64 array, which also makes sense, but I'd like a float32 array, so I tried:
N.where(a >= 5, array(5.0, dtype=N.float32), 0)
but I got a float64 array again.
How can I get a float32 array? where doesn't take a dtype argument -- maybe it should?
You need to do N.where(a >= 5, N.float32(5), N.float32(0)) The rules are the same as for ufuncs: The returned array for mixed-type operations uses the "largest" type unless one is a scalar and one is an array (then the scalar is ignored unless the "kind" is different). In this case, you have two scalars (a 0-d array is considered a scalar in this context. -Travis
Chris Barker wrote:
Hi all,
I'd like to set the data type for what numpy.where creates. For example:
import numpy as N
N.where(a >= 5, 5, 0)
creates an integer array, which makes sense.
N.where(a >= 5, 5.0, 0)
creates a float64 array, which also makes sense, but I'd like a float32 array, so I tried:
N.where(a >= 5, array(5.0, dtype=N.float32), 0)
but I got a float64 array again.
Well, it's consistent with all of the other coercion rules: In [6]: (array(5.0, dtype=float32) + 0).dtype Out[6]: dtype('float64') float64 is the lowest floating point dtype that can hold the full range of int32 values (much less int64) without losing precision. Since both operands ("coercands"?) are scalars, they both get a say in the final dtype (unlike a full array being coerced together with a scalar; only the array gets a say). -- 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
Robert Kern wrote:
Well, it's consistent with all of the other coercion rules:
In [6]: (array(5.0, dtype=float32) + 0).dtype Out[6]: dtype('float64')
duh! of course. If I use a float32 scalar for BOTH the operands, then I get a float32 array out. Thanks, -Chris -- Christopher Barker, Ph.D. Oceanographer Emergency Response Division NOAA/NOS/OR&R (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker@noaa.gov
participants (4)
-
Chris Barker -
Christopher Barker -
Robert Kern -
Travis Oliphant