mantissa and exponent in base 10

  • Thread starter Steven D'Aprano
  • Start date
S

Steven D'Aprano

I want the mantissa and decimal exponent of a float, in base 10:

mantissa and exponent of 1.2345e7
=> (1.2345, 7)

(0.12345, 8) would also be acceptable.


The math module has a frexp() function, but it produces a base-2 exponent:
(0.73581933975219727, 24)

Have I missed a built-in or math function somewhere?
 
R

Robert Kern

I want the mantissa and decimal exponent of a float, in base 10:

mantissa and exponent of 1.2345e7
=> (1.2345, 7)

(0.12345, 8) would also be acceptable.


The math module has a frexp() function, but it produces a base-2 exponent:

(0.73581933975219727, 24)

Have I missed a built-in or math function somewhere?

|7> def frexp10(x):
...> exp = int(math.log10(x))
...> return x / 10**exp, exp
...>

|8> frexp10(1.2345e7)
(1.2344999999999999, 7)

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
U

Ulrich Eckhardt

Steven said:
I want the mantissa and decimal exponent of a float, in base 10:

mantissa and exponent of 1.2345e7
=> (1.2345, 7)

(0.12345, 8) would also be acceptable. [...]
Have I missed a built-in or math function somewhere?

The integral, decimal exponent is just the floor/ceiling of log10 of that
number.

Uli
 
D

Dave Angel

I want the mantissa and decimal exponent of a float, in base 10:

mantissa and exponent of 1.2345e7
=> (1.2345, 7)

(0.12345, 8) would also be acceptable.


The math module has a frexp() function, but it produces a base-2 exponent:

(0.73581933975219727, 24)

Have I missed a built-in or math function somewhere?
First point is that this is a conversion, since the float is stored
internally using a binary exponent. So anything you do with logs might
just give roundoff errors, one way or another. I'd therefore suggest
converting the number explicitly, using whatever approach is appropriate
to the further processing of the number.

If you want the version that will display, then convert it to a string,
and parse that.

If you want to do further processing, use the decimal module to convert
it. Once it's converted, there's an as_tuple() method that will give
you an exact representation of the original value. That may not be the
same mantissa as you'd get with the original, and for numbers like
9.99999999 or whatever, this could be significant.

DaveA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top