0

How can I convert a number in scientific notation to a tuple that contains the significand and the exponent? For example:

4e+3(4, 3)

4e-3(4, -3)

Sid-Ali
  • 7
  • 4
  • https://stackoverflow.com/questions/8593355/how-do-i-count-the-trailing-zeros-in-integer – Chris Sep 28 '21 at 12:41
  • `math.frexp()` sort of does this, although it returns the exponent as a power of 2 instead of a power of 10 (since that's how floats are actually stored). – jasonharper Sep 28 '21 at 13:24
  • its not really what i am looking for @Chris i mean it works for trailling '0' but in we put '4321' it dosent return (4.321, -3) – Sid-Ali Sep 28 '21 at 14:43

2 Answers2

1

you could use

def scientific_to_tuple (float_number)
    # Assume that float_number = 0.0034
    scientific_string = f"{float_number:e}"
    # after that, scientific_string looks like '3.400000e-03'
    return tuple([float(item) for item in scentific_string.split("e")])

edit Note: I was tired so the method returned string. I fixed it. Actually, if tuple is not required, you can omit tuple casting. like

return [float(item) for item in scentific_string.split("e")]
  • actually its not what i am looking for i want to return a tuple just like the example this code returns an array for example if i do `scientific_to_tuple(4000)` i get `['4.000000', '+03']` i wanted it to be like `(4, 3)` – Sid-Ali Sep 28 '21 at 12:57
  • sorry. I fixed it. now, it return tuple. But actually it doesn't matter for this solution. – Ahmet Dundar Sep 28 '21 at 13:20
  • @Sid-Ali sorry. I was tired so I missed that actually the method returned string, not float. I fixed it. – Ahmet Dundar Sep 29 '21 at 07:03
  • it works now thank you for your time mate ;) – Sid-Ali Sep 29 '21 at 22:01
0

Maybe you want this modified version of Ahmet Dundar's answer:

def scientific_to_tuple (float_number):
    scientific_string = f"{float_number:e}"
    a, b = scientific_string.split("e")
    f = float(a)
    i = int(f)
    a = i if f == i else f
    return (a, int(b))
  • it works only when we have a positve exponent what if we put `scientific_to_tuple(4.323)` it returns `(4.323, 0)` instead of `(4323, -3)` do u see the point ? i might explain bad due to my bad english sorry for that – Sid-Ali Sep 28 '21 at 14:02
  • I recommend to examine [scientific notation](https://en.wikipedia.org/wiki/Scientific_notation). `scientific_to_tuple(4.323)` should also return `(4.323, 0)` – Muhammed YILMAZ Sep 29 '21 at 05:44