0

I came across the following strange result in Python (I use Spyder environment). Any idea what is going on? And how can I fix this? I truly don't want to put 20 zeros in front of my variable nor using numpy for such a simple work makes sense!

int(121212000000000000000000000000000000000000000000000000)
Out[27]: 121212000000000000000000000000000000000000000000000000

int(121212*1e20)
Out[28]: 12121199999999999802867712

int(121212*10e20)
Out[29]: 121211999999999993733709824
Jab
  • 26,853
  • 21
  • 75
  • 114
Hadi Rohani
  • 215
  • 4
  • 14
  • 3
    This isn't weird. `121212*1e20` creates a float. Fixed size, binary floating point representations have inherent limitations to their precision. In this case, you can just do `121212*int(1e20)`, or, just do `121212*10**20` – juanpa.arrivillaga Sep 10 '20 at 22:32
  • Thank you Jab, that answered my question! I think I should learn more about floats and their limitations. – Hadi Rohani Sep 12 '20 at 22:16

1 Answers1

1

It has to do with floating point precision.

You can use the decimal module like so:

>>> from decimal import Decimal
>>> Decimal(121212) * Decimal('10e20')
Decimal('121212000000000000000000000')

For more info, see the following Python tutorial.

Bharel
  • 23,672
  • 5
  • 40
  • 80
  • 1
    Sorry, this is not a general soultion. With `Decimal(10e20)` you are instantiating `Decimal` from a float. Try it with a different (higher) power and see what happens. Also you are out by a factor of 10. (`Decimal(121212) * Decimal('1e20')` would be okay - or just `Decimal('121212e20')`) – alani Sep 10 '20 at 22:49
  • True, I didn't mind about the specifics, but it is the solution to his issue. I edited my answer a little. – Bharel Sep 10 '20 at 22:58