Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 there a BRIEF way to accomplish this without resorting to string conversions or using a for loop to determine the exponent? Writing such a function wouldn't be difficult, I'm just shocked that I'm having trouble finding an existing one in math, decimal or numpy.

e.g. if fexp and fman are the functions giving the exponent and mantissa of the decimal floating point representation of a float then we'd expect the following statements to all return true:

fexp(154.3) == 2.0
fman(154.3) == 1.543
fexp(-1000) == 3.0
fman(-1000) == -1.0

In short, this would be a "decimal version" of math.frexp.

like image 329
jpm Avatar asked Jul 26 '17 16:07

jpm


People also ask

How do you extract mantissa and exponent from float?

Python | frexp() Function frexp() function is one of the Standard math Library function in Python. It returns mantissa and exponent as a pair (m, e) of a given value x, where mantissa m is a floating point number and e exponent is an integer value. m is a float and e is an integer such that x == m * 2**e exactly.

What is the mantissa of a float?

The mantissa represents the actual binary digits of the floating-point number. The power of two is represented by the exponent. The stored form of the exponent is an 8-bit value from 0 to 255.


1 Answers

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.

like image 144
jsalonen Avatar answered Oct 01 '22 09:10

jsalonen