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