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

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐