Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the size of a float in python?

Tags:

python

numpy

I want to check whether a float is actually 32 or 64bits (and the number of bits of a numpy float array). There should be a built-in, but just didn't find out...

like image 549
Hailiang Zhang Avatar asked Nov 21 '11 17:11

Hailiang Zhang


People also ask

How do you check the length of a float in Python?

To get the length of a float in Python:Use the str() class to convert the float to a string, e.g. result = str(my_float) . Pass the string to the len() function, e.g. len(result) . The len() function will return the length of the string.

Is Python float 32 or 64?

Python's floating-point numbers are usually 64-bit floating-point numbers, nearly equivalent to np.

What is the precision of float in Python?

Python Decimal default precision The Decimal has a default precision of 28 places, while the float has 18 places.


2 Answers

Properties of a Python float can be requested via sys.float_info. It returns information such as max/min value, max/min exp value, etc. These properties can potentially be used to calculate the byte size of a float. I never encountered anything else than 64 bit, though, on many different architectures.

The items of a NumPy array might have different size, but you can check their size in bytes by a.itemsize, where a is a NumPy array.

like image 89
Sven Marnach Avatar answered Oct 05 '22 13:10

Sven Marnach


numpy.finfo lists sizes and other attributes of float32 ..., including
nexp : number of bits in the exponent including its sign and bias.
nmant : number of bits in the mantissa.
On a machine with IEEE-754 standard floating point,

import numpy as np for f in (np.float32, np.float64, float):     finfo = np.finfo(f)     print finfo.dtype, finfo.nexp, finfo.nmant 

will print e.g.

float32 8 23 float64 11 52 float64 11 52 

(Try float16 and float128 too.)

like image 43
denis Avatar answered Oct 05 '22 12:10

denis