Ivelin
Ivelin

Reputation: 13329

float64 to float32 conversion gives unexpected result

When I convert a float64 number to a float32 number I get a weird result:

In [22]: np.float32(20140131.0)
Out[22]: 20140132.0

Why is this happening?

Upvotes: 7

Views: 4126

Answers (1)

will
will

Reputation: 10650

20140131.0 can't be represented as a 32 bit integer.

32 bit float

64 bit float

With floats, within each range, the numbers are evenly spaced.

So it's (1+M) * 2^(E)

so 20140131.0 is in the range of 2^24 to 2^25. There are 16,777,216 numbers in that range, but only 8,388,608 representable floats. So you can only represent even numbers.

Since in 32bit floats, there are only 23 bits for the mantissa, integers can only be represented up to 2^24. Above that, epsilon > 1. Where epsilon is the difference between two adjacent floating point numbers.

As for python floats, i believe they work like this:

Floats in python are typically not 32 bit, or 64 bit, so this isn't a problem. The length is adjusted automatically. Buy you're casting them to specific types, so you see the lack of resolution. With 64bit integers, there are 52 bits in the mantissa, so you will not see this problem until you go above 2^53.

Also, the way the number is rounded to the nearest float is normally defined in a system wide manner (i think), but python's casting may over rule this, i'm not completely familiar with it.

Upvotes: 9

Related Questions