简体   繁体   中英

Numpy - float32 gives different value from dtype=“float32” in array

Numpy Float32 value is different depending on whether initiated inside an array or as a standalone float32:

>>> numpy.array([75.09], dtype="float32")
array([ 75.08999634], dtype=float32)
>>> numpy.float32(75.09)
75.089996

I need to be able to search the array for the float32 value. Currently value is not found because of the last two extra digits. I have also tried:

>>> numpy.array([75.09], dtype="float32").round(decimals=6)
array([ 75.08999634], dtype=float32)

And:

>>> numpy.around(numpy.array([75.09], dtype="float32"), decimals=6)
array([ 75.08999634], dtype=float32)

But as you can see output still contains the last two digits.

The numbers are (most likely) the same, it's just a matter of how the objects are formatted as strings.

>>> numpy.array([75.09], dtype="float32")[0] == numpy.float32(75.09)
True

The problem (as you may already know) is that 75.09 seems to require a lot of precision, maybe even infinite (I didn't do the math, more about it here ).

If you want to have consistent text output just use your own string formatting.

>>> a = numpy.array([75.09], dtype="float32")
>>> b = numpy.float32(75.09)
>>> print 'a: [', ','.join('{:.6f}'.format(ai) for ai in a), '] b:','{:.6f}'.format(b)
a: [ 75.089996 ] b: 75.089996
>>> print 'a: [', ','.join('{:.8f}'.format(ai) for ai in a), '] b:','{:.8f}'.format(b)
a: [ 75.08999634 ] b: 75.08999634

The display of the numbers is different because they are printed as a NumPy array (1) and and float (2). Try to print the first array member numpy.array([75.09], dtype="float32")[0] .

Comments about the finite precision of floating point numbers are also to take into account :-) Almost never will you find equality in floating point numerics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM