【问题标题】:why is 1e400 not an int?为什么 1e400 不是整数?
【发布时间】:2016-07-05 16:04:03
【问题描述】:

为什么科学计数法中的数字总是读作float,我如何将像'1e400'这样的字符串转换为int(对于float来说太大了)?

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

我知道,我可以制作如下函数:

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`

但这不是一个非常pythonic的方法,有没有更好的方法?

【问题讨论】:

  • @snakecharmerb 该问题的答案都假设该数字在float 的范围内,而这个问题明确表示不是。
  • 至于为什么e 表示法总是被视为浮点数,那只是因为语法是这样定义的。你无法改变它。
  • @Mark Ransom,但作为一个人类,我将此数字读取为 int,而 xrange(2e6) 读取为 xrange(2000000) 的速度更快,而且出错的空间更小。
  • @12431234123412341234123 我很同情。对于合理范围内的数字,例如int(2e6) 效果很好。

标签: python floating-point int scientific-notation


【解决方案1】:

也许您可以在转换为 int 之前使用 Decimal 作为中间类型。

>>> import decimal
>>> decimal.Decimal("1e400")
Decimal('1E+400')
>>> int(decimal.Decimal("1e400"))
10000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0

【讨论】:

    猜你喜欢
    • 2014-12-12
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 2014-09-27
    • 2016-02-18
    相关资源
    最近更新 更多