在 Python 2.7 中将无穷大表示为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40445920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:33:53  来源:igfitidea点击:

Represent infinity as an integer in Python 2.7

pythonpython-2.7infinity

提问by Lin Ma

I am wondering how to define infand -infas an intin Python 2.7. I tried and it seems infand -infonly work as a float.

我想知道如何在 Python 2.7 中定义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'

回答by Jezzamon

To summarise what was said in the comments

总结评论中的内容

There is no way to represent infinity as an integer in Python. This matches the behaviour of many other languages. However, due to Python's dynamic typing system, you can use float('inf')in place of an integer, and it will behave as you would expect.

在 Python 中无法将无穷大表示为整数。这与许多其他语言的行为相匹配。但是,由于 Python 的动态类型系统,您可以使用float('inf')整数来代替,并且它的行为将与您预期的一样。

As far as creating a 'double' for infinity, in Python there is just one floating point type, called float, unlike other languages such as Java which uses the term float and double for floating point numbers with different precision. In Python, floating point numbers usually use double-precision, so they act the same as doubles in Java.

至于为无穷大创建“double”,在 Python 中只有一种浮点类型,称为float,与 Java 等其他语言不同,Java 使用术语 float 和 double 表示具有不同精度的浮点数。在 Python 中,浮点数通常使用 double-precision,因此它们的作用与 Java 中的 double 相同。

回答by Matthy Playz

Something very big that is a integer (made in 3.x, not tested in 2.x):

一些非常大的整数(在 3.x 中制作,未在 2.x 中测试):

0x40000 #will most likely crash the shell

so if you wanted a infinite variable you would do:

所以如果你想要一个无限变量,你会这样做:

Infinity = 0x40000

You can do any Integer to Hexedecimal here:
https://www.binaryhexconverter.com/decimal-to-hex-converter
(make sure to add the 0xbefore the value it returns for python)

你可以在这里做任何整数到十六进制:
https://www.binaryhexconverter.com/decimal-to-hex-converter
(确保0x在它为python返回的值之前添加)