Extracting the exponent from scientific notation
Asked Answered
M

1

9

I have a bunch of numbers in scientific notation and I would like to find their exponent. For example:

>>> find_exp(3.7e-13)
13

>>> find_exp(-7.2e-11)
11

Hence I only need their exponent ignoring everything else including the sign.

I have looked for such a way in python but similar questions are only for formatting purposes.

Madera answered 3/10, 2020 at 11:37 Comment(5)
why dont you convert them to a string as they are. Then use regex to extract the last part after the dash. Then you can convert back to number.Mamiemamma
that is not an option. Likewise, I could have split the string after converting it to a regular floatMadera
And why is it not an option? Also splitting on the dash would be a bit shaky because it could be signed with a minus and unsigned. You would need to include this in your check.Mamiemamma
It seems the input is already in string format (cf. the quotes).Boudreau
What are some of the other strings you have? Do some have more than one digit before the decimal point, like "26.3e-10", or is the notation always normalized? Secondly, what would be the answer for "1.1111111111e2"?Boudreau
G
13

Common logarithm is what you need here, you can use log10 + floor:

from math import log10, floor

def find_exp(number) -> int:
    base10 = log10(abs(number))
    return abs(floor(base10))

find_exp(3.7e-13)
# 13

find_exp(-7.2e-11)
# 11
Georgeta answered 3/10, 2020 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.