Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float64 to float32 conversion gives unexpected result

Tags:

python

numpy

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?

like image 932
Ivelin Avatar asked May 20 '14 22:05

Ivelin


People also ask

What is the difference between float64 and float32?

float32 is a 32 bit number - float64 uses 64 bits. That means that float64's take up twice as much memory - and doing operations on them may be a lot slower in some machine architectures. However, float64's can represent numbers much more accurately than 32 bit floats. They also allow much larger numbers to be stored.

What is float64 in Python?

Python float values are represented as 64-bit double-precision values. 1.8 X 10308 is an approximate maximum value for any floating-point number. If it exceeds or exceeds the max value, Python returns an error with string inf (infinity).


1 Answers

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.

like image 55
will Avatar answered Sep 20 '22 12:09

will