ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-25 12:57:23  阅读:249  来源: 互联网

标签:logarithm floating-point python


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有