0

I am trying to figure out a way to write 21*(10^21) in Python. I've tried two approaches. The first one is simply by doing the following:

>>> print(21*(10**21))
21000000000000000000000

This works just fine. However, the problem I'm trying to solve requires me to get to this number by iteration, i.e, by building up from 1*(10^1) all the way to 21*(10^21). So I tried the following:

>>> temp = 20*(10**20)
>>> print(21*temp*10/20)
2.1e+22

Now, I want the entire number to show up, and not in the 'e' form, so I converted it to int. But this prints the wrong answer:

>>> print(int(21*temp*10/20))
20999999999999997902848

I know that integers don't have a limit in Python 3 (which is what I'm using) so this baffles me. I thought this may be because the /20 part causes conversion to float, but the number 21*(10^21) falls within the limits of float, so converting back to int shouldn't be a problem.

I've tried searching for this error online with no luck. Any help would be appreciated.

  • 2
    Even for values within its range, floats still have limited precision. – khelwood Apr 15 '20 at 08:04
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – FlyingTeller Apr 15 '20 at 08:05
  • If I recall correctly, `/` in Python 3 produces a floating-point result, but `//` produces an integer result. Try `21*temp*10//20`. – Eric Postpischil Apr 15 '20 at 11:11
  • @FlyingTeller: This is not a duplicate of that question, as this question involves largely Python type semantics. Please do not promiscuously mark questions as a duplicate of that one. – Eric Postpischil Apr 15 '20 at 11:12

0 Answers0