Lay out the float in mantissa and the exponent in base 10 without strings

Are there functions in the Python or numpy library that take a float as input and return a decimal scientific notation decomposition, i.e. mantissa and exhibitor? Or is there a SHORT way to achieve this without resorting to string conversion or using a for loop to determine the exponent? Writing such a function will not be difficult, I am simply shocked that it is difficult for me to find the existing one in mathematics, decimal or numpy.

eg. if fexp and fman are functions that give the exponent and mantissa of a decimal floating-point number for float, then we expect all statements to return true:

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

In short, it will be the “decimal version” of math.frexp .

+5
source share
3 answers

One way to avoid string conversion is to implement 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() 

Please note that using floating point numbers it is impossible to calculate it with the mantissa and exponent without rounding. The reason is that floating point numbers are stored as fractional parts of 2. For example, the stored float value for 154.3 is 154.30000000000001136868377216160297393798828125 . Floats are displayed in the console as exact numbers because (in CPython) they are always rounded when serialized using hard-coded precision of 17 .

+7
source

I hope for a better answer, but 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) 
+2
source

For base 10, my solution was:

 mantissa, exponent = [float(y) for y in str(x).split('e')] 

where x is the float that you are trying to decompose.

0
source

Source: https://habr.com/ru/post/1270233/


All Articles