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

前端 未结 2 1162
生来不讨喜
生来不讨喜 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.

提交回复
热议问题