Python floating-point precision format specifier

后端 未结 2 1233
一生所求
一生所求 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:00

    I am not exactly sure what you are trying to accomplish. However, this might help. You wrote

    This seems to work reasonably well, but the precision number is also used up for numbers in front of the decimal place too, e.g. 34567.375768.

    You can use %f instead of g. From the Python docs:

    The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'.

    >>> z = np.float64(4.555555555555555)
    >>> "%.3f" % z
    '4.556'
    >>> q = np.float64(2131234.555555555555555)
    >>> "%.3f" % q
    '2131234.556'
    >>>
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题