Python 小技巧:Python3 表示最大整数值和浮点数值

来源:互联网 发布:小学生笔顺软件下载 编辑:程序博客网 时间:2024/06/05 13:22

一、引言

这是我在学习 《Python Algorithms 2nd》 一书中第 28 页时候受到的启发:

For intergral weights, you could use sys.maxint , even though it’s not guaranteed to be the greatest possbile value (long ints can be longer).

我们废话少说,直接测试代码:

import sysprint(sys.maxint)

我们满心期待着以为可以输出最大的整数数值,结果发现报错了:

Traceback (most recent call last):
File “”, line 1, in
AttributeError: module ‘sys’ has no attribute ‘maxint’

那么,这是为什么呢?

二、探索

中文社区有关这个问题的探索很少,于是我找到了 StackOverflow 上的外国友人的描述:

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any pratical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

也就是说,在新版本的发行版中,sys.maxint 已经被去掉了,因为对于整型数值再也没有限制了。但是呢,标准又提供了 sys.maxsize 来表示一个大于任何我们实际工作中能够表示的最大的整型数值。这个值正好与原来的 sys.maxint 相同。

那么,就让我们测试下:

import sysprint(sys.maxsize)

在我的机器上,运行结果为:

9223372036854775807

另外,想要表达最大的浮点数值,可以:

print(float('inf'))

上述表达式输出:

inf

用于表达无限大的浮点数值。

三、总结

其实就是两句话:

sys.maxsize

float(‘inf’)

简单易记,方便使用:)

原创粉丝点击