Stefano Borini
Stefano Borini

Reputation: 143795

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 ?

Upvotes: 5

Views: 693

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601599

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.

Upvotes: 6

NPE
NPE

Reputation: 500327

There isn't a built-in type in Python that's represented using 32-bit floats.

However, see Sven Marnach's answer for alternatives.

Upvotes: 1

Related Questions