为什么在python中整数的值没有限制_python-为什么math.log接受大整数值?

这篇博客揭示了Python如何处理大型整数的对数计算。Python的mathlib库利用loghelper函数,即使可能有中间溢出,也能为巨大的整数计算对数。当传入的参数是整数时,Python会避免使用libm,而是自行计算。这种方法确保了结果的准确性,尽管其他某些函数如sqrt可能无法处理这种情况。此特性在Python的源代码中有详细记录,但未在官方文档中明确说明。
摘要由CSDN通过智能技术生成

我终于钻入python math lib source code,发现了这一点:

/* A decent logarithm is easy to compute even for huge ints, but libm can't

do that by itself -- loghelper can. func is log or log10, and name is

"log" or "log10". Note that overflow of the result isn't possible: an int

can contain no more than INT_MAX * SHIFT bits, so has value certainly less

than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is

small enough to fit in an IEEE single. log and log10 are even smaller.

However, intermediate overflow is possible for an int if the number of bits

in that int is larger than PY_SSIZE_T_MAX. */

static PyObject*

loghelper(PyObject* arg, double (*func)(double), const char *funcname)

{

/* If it is int, do it ourselves. */

if (PyLong_Check(arg)) {

double x, result;

Py_ssize_t e;

...

我会保留其余的源代码(检查链接),但是据我了解,Python会检查传递的参数是否为整数,如果是,则不要使用math lib(如果为int,自己做.)评论.另外:即使对于很大的整数,也很容易计算出不错的对数,但是libm本身不能做到这一点-loghelper可以

如果是双精度数,则调用本地数学库.

从源注释中可以看出,即使发生溢出,Python也会尽最大努力提供结果(此处转换为两次溢出,但仍可以计算日志.清除异常并继续)

因此,由于使用了log函数的python包装,Python能够计算巨大整数的对数(特定于某些函数,因为sqrt等其他函数无法做到),并且已在文档中进行了记载,但仅在源代码中有记录.正如Jon所暗示的那样,使其成为实现细节.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值