Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python floating point nature and converting to a smaller type

I am trying to understand the exact nature of float when it comes to python. Apparently, python stores floats in a PyFloatObject type which contains a double. However, how can I force it to behave like a 32 bit floating point variable ? Is there another type for this ?

like image 907
Stefano Borini Avatar asked Mar 18 '11 15:03

Stefano Borini


People also ask

How do you convert a float to an integer in Python?

Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 . When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer.

How do you fix a floating-point error in Python?

An alternative is to stick to floats and add something that is exactly representable as a binary float: values of the form I/2**J . For example, instead of adding 0.01, add 0.125 (1/8) or 0.0625 (1/16).

Why are floating-point calculations so inaccurate in Python?

Because often-times, they are approximating rationals that cannot be represented finitely in base 2 (the digits repeat), and in general they are approximating real (possibly irrational) numbers which may not be representable in finitely many digits in any base.

Can float type in python3 can represent decimal 0.1 without error?

Some values cannot be exactly represented in a float data type. For instance, storing the 0.1 value in float (which is a binary floating point value) variable we get only an approximation of the value. Similarly, the 1/3 value cannot be represented exactly in decimal floating point type.


1 Answers

The built-in float type of Python always uses double precision (unless you compile a custom version of the interpreter). You can use the array module to get 32-bit floats:

a = array.array("f")

will define an array of 32-bit floats.

The external NumPy package also provides a scalar 32-bit floating-point type, namely numpy.float32.

like image 52
Sven Marnach Avatar answered Sep 25 '22 00:09

Sven Marnach