How to check the size of a float in python?

前端 未结 5 1180
感动是毒
感动是毒 2020-12-17 08:41

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...

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 09:04

    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.)

提交回复
热议问题