why is 1e400 not an int?
Asked Answered
F

1

7

Why is a number in Scientific notation always read as a float, and how can i convert a string like '1e400' to an int (which is too large for a float) ?

>>>int('1e400') 
ValueError: invalid literal for int() with base 10: '1e400'
>>>int(float('1e400'))
OverflowError: cannot convert float infinity to integer

i know, i can make a function like:

def strtoint(string):
  parts = string.split('e')
  if len(parts) == 1:
    return int(string)
  elif len(parts) == 2:
    if int(parts[1])<0:
      return int(string)
    return int(parts[0])*10**int(parts[1])
  else:
    return int(string) #raise a error if the string is invalid, but if the variable string is not a string, it may have other way to convert to an `int`

But this not a very pythonic way, is there a better way?

Foust answered 18/3, 2016 at 18:50 Comment(4)
@snakecharmerb the answers to that question all assume that the number is within the range of a float, while this question explicitly says it is not.Ovule
As for why e notation is always treated as a float, that's just because the syntax is defined that way. Nothing you can do to change it.Ovule
@Mark Ransom, but as a human, i read this number as a int, and xrange(2e6) its faster to read as xrange(2000000) and there is less room for errors.Foust
@Foust I sympathize. For numbers that are in a reasonable range, int(2e6) for example works great.Ovule
D
10

Perhaps you could use Decimal as an intermediary type before converting to int.

>>> import decimal
>>> decimal.Decimal("1e400")
Decimal('1E+400')
>>> int(decimal.Decimal("1e400"))
10000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0
Devilkin answered 18/3, 2016 at 18:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.