Python floating-point precision format specifier

后端 未结 2 1296
一生所求
一生所求 2021-02-06 03:46

Let\'s say I have some 32-bit numbers and some 64-bit numbers:

>>> import numpy as np
>>> w = np.float32(2.4)
>>> x = np.float32(4.555         


        
2条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 04:13

    You could try to use the np.finfo function to get the precision corresponding to your float

    finfo32 = np.finfo(np.float32)
    finfo64 = np.finfo(np.float64)
    
    finfo32.resolution = 1e-6
    finfo64.resolution = 1e-15
    

    Now that you know how many decimals you want, say, 6, just use a rstrip("0") to get rid of the unnecessary 0s:

    print ("%.6f" % your_float).strip("0")
    

    If you're leaning towards %g, perhaps you may want to use a dynamic format such as:

    >>> strf = lambda v: ("%%.%ig" % max(np.ceil(np.log10(v)), 7)) % v
    >>> strf(123.456789)
    '123.45679'
    >>> strf(123456789.12345)
    '123456789'
    

提交回复
热议问题