Decompose a float into mantissa and exponent in base 10 without strings

前端 未结 2 1138
生来不讨喜
生来不讨喜 2021-01-02 00:02

Are there functions in the Python library or numpy that take a float as input and return its decimal scientific notation decomposition, i.e. mantissa and exponent? Or is the

相关标签:
2条回答
  • 2021-01-02 00:20

    One way to avoid string conversions is to implement the methods using Decimals:

    from decimal import Decimal
    
    def fexp(number):
        (sign, digits, exponent) = Decimal(number).as_tuple()
        return len(digits) + exponent - 1
    
    def fman(number):
        return Decimal(number).scaleb(-fexp(number)).normalize()
    

    Note that using floating point numbers, its not possible to calculate mantissa and exponent without rounding. The reason is that floating point numbers are stored as base 2 fractions. For example stored float value for 154.3 is 154.30000000000001136868377216160297393798828125. Floats are displayed in console as accurate numbers, because (in CPython) they are always rounded when serialized using a hard-coded precision of 17.

    0 讨论(0)
  • 2021-01-02 00:38

    I'm hoping there's a better answer but I came up with

    from math import floor, log10
    
    def fexp(f):
        return int(floor(log10(abs(f)))) if f != 0 else 0
    
    def fman(f):
        return f/10**fexp(f)
    
    0 讨论(0)
提交回复
热议问题