编程语言
首页 > 编程语言> > python-为什么math.log接受大整数值?

python-为什么math.log接受大整数值?

作者:互联网

from math import log,sqrt
import sys
n = 760 ** 890
print(log(n))

我得到一个有效的结果.

现在按sqrt更改日志,您将得到(如预期的那样):

OverflowError: int too large to convert to float

所以我想在日志函数中有一个使用整数对数的整数参数技巧,但是我没有在文档中找到.只有this

math.log(x[, base])

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

记录在哪里?

解决方法:

我终于钻入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所暗示的那样,使其成为实现细节.

标签:logarithm,floating-point,python
来源: https://codeday.me/bug/20191025/1928804.html