在 Python 2.7 中将无穷大表示为整数 [英] Represent infinity as an integer in Python 2.7

查看:76
本文介绍了在 Python 2.7 中将无穷大表示为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 Python 2.7 中将 inf-inf 定义为 int.我试过了,似乎 inf-inf 只能用作 float.

I am wondering how to define inf and -inf as an int in Python 2.7. I tried and it seems inf and -inf only work as a 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') 代替整数,并且在大多数情况下它的行为与您预期的一样.

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 in most situations it will behave as you would expect.

至于为无穷大创建double",在 Python 中只有一种浮点类型,称为 float,这与 Java 等其他语言不同,它使用术语 float 和 double 来表示浮点不同精度的数字.在 Python 中,浮点数通常使用双精度,所以它们的作用与Java中的双精度相同.

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.

这篇关于在 Python 2.7 中将无穷大表示为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆