[英]Represent infinity as an integer in Python 2.7
我想知道如何在 Python 2.7 -inf
inf
和-inf
定义为int
。 我试过了,似乎inf
和-inf
只能用作float
。
a = float('-inf') # works
b = float('inf') # works
c = int('-inf') # compile error, ValueError: invalid literal for int() with base 10: 'inf'
d = int('inf') # compile error, ValueError: invalid literal for int() with base 10: 'inf'
总结评论中的内容
在 Python 中无法将无穷大表示为整数。 这与许多其他语言的行为相匹配。 但是,由于 Python 的动态类型系统,您可以使用float('inf')
代替整数,并且在大多数情况下它会按您的预期运行。
至于为无穷大创建“double”,在 Python 中只有一种浮点类型,称为float
,这与 Java 等其他语言不同,Java 使用术语 float 和 double 表示具有不同精度的浮点数。 在 Python 中, 浮点数通常使用 double-precision ,因此它们的作用与 Java 中的 double 相同。
一些非常大的整数(在 3.x 中制作,未在 2.x 中测试):
0x40000 #will most likely crash the shell
所以如果你想要一个无限变量,你会这样做:
Infinity = 0x40000
您可以在此处将任何整数转换为十六进制:
https://www.binaryhexconverter.com/decimal-to-hex-converter
(确保在为 python 返回的值之前添加0x
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.