将科学计数形式的数字转换为int [英] Converting number in scientific notation to int
问题描述
有人可以解释为什么我不能使用int()
将以字符串科学符号表示的整数转换为python int
吗?
例如,这不起作用:
print int('1e1')
但是确实如此:
print int(float('1e1'))
print int(1e1) # Works
为什么int
无法将字符串识别为整数?它肯定和检查指数的符号一样简单吗?
在幕后,科学数字表示法始终在内部表示为float.原因是变化的数字范围,因为整数仅映射到固定值范围,例如2^32
值.科学表示形式类似于具有重要意义和指数意义的浮动表示形式.您可以在 https://en.wikipedia.org/wiki/Floating_point 中查找更多详细信息. /p>
您不能将科学数字表示形式直接转换为字符串作为整数.
print int(1e1) # Works
有效,因为1e1
作为数字已经是浮点数.
>>> type(1e1)
<type 'float'>
回到您的问题:我们想从float或科学字符串中获取一个整数.详细信息: https://docs.python.org/2/reference/lexical_analysis.html #integers
>>> int("13.37")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '13.37'
对于浮点表示或科学表示,您必须在float
上使用中间步骤.
Could someone explain why I can not use int()
to convert an integer number represented in string-scientific notation into a python int
?
For example this does not work:
print int('1e1')
But this does:
print int(float('1e1'))
print int(1e1) # Works
Why does int
not recognise the string as an integer? Surely its as simple as checking the sign of the exponent?
Behind the scenes a scientific number notation is always represented as a float internally. The reason is the varying number range as an integer only maps to a fixed value range, let's say 2^32
values. The scientific representation is similar to the floating representation with significant and exponent. Further details you can lookup in https://en.wikipedia.org/wiki/Floating_point.
You cannot cast a scientific number representation as string to integer directly.
print int(1e1) # Works
Works because 1e1
as a number is already a float.
>>> type(1e1)
<type 'float'>
Back to your question: We want to get an integer from float or scientific string. Details: https://docs.python.org/2/reference/lexical_analysis.html#integers
>>> int("13.37")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '13.37'
For float or scientific representations you have to use the intermediate step over float
.
这篇关于将科学计数形式的数字转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!