Reputation: 63
I was having trouble using numpy.average, it hit an error every time until I converted the inputs to numpy.float64s. I had a look at the source and it's because of the following behaviour, what's the reason for the difference?
>>> f, f32 = numpy.float(1.0), numpy.float32(1.0)
>>> (f == 1.0).any()
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
(f == 1.0).any()
AttributeError: 'bool' object has no attribute 'any'
>>> (f32 == 1.0).any()
True
Upvotes: 1
Views: 158
Reputation: 1065
It's because a numpy.float32
object doesn't return a bool
object upon comparison with __eq__
, but a numpy.bool_
one.
>>> type((f == 1.0))
<type 'bool'>
>>> type((f32 == 1.0))
<type 'numpy.bool_'>
Upvotes: 1
Reputation: 231325
You don't normally need to use expressions like numpy.float(1.0)
.
The most common, basic operation in numpy
is to make an array.
f = np.array([1.0, 1.23])
mf = f.mean() # or
mf = np.mean(f)
or with integers
f = np.array([1, 3, 5, 3, 5])
f==3
(f==3).any()
Note I am using integers with ==
test. ==
test is not a good idea when using floats.
I could go further and specify the dtype
:
f = np.arange(5, dtype=int)
f = np.ones((3,4), dtype=float)
Individual items of these arrays will be of type np.float
, np.int
, etc. There's rarely a need to create one directly np.float(1.23)
. Specify the dtype
when creating an array, but otherwise let numpy
take care of those details.
Upvotes: 0
Reputation: 2028
>>> type(numpy.float32(1.0))
<type 'numpy.float32'>
>>> type(numpy.float(1.0))
<type 'float'>
>>> type(numpy.float32(1.0) == 1.0)
<type 'numpy.bool_'>
>>> type(numpy.float(1.0) == 1.0)
<type 'bool'>
The numpy.float32
and numpy.bool_
are used to not only store scalar but also vector:
>>> numpy.float32([1.0, 2.0])
array([ 1., 2.], dtype=float32)
>>> numpy.float32([1.0, 2.0]) == 1.0
array([ True, False], dtype=bool)
So there is an any()
function in numpy.bool_
to check whether any of the items is True.
Upvotes: 2