np.power完成了哪些其他工作? [英] What additional work is done by np.power?

查看:69
本文介绍了np.power完成了哪些其他工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到np.power(a, b)np.exp(b * np.log(a))慢:

import numpy as np
a, b = np.random.random((2, 100000))
%timeit np.power(a, b) # best of 3: 4.16 ms per loop
%timeit np.exp(b * np.log(a)) # best of 3: 1.74 ms per loop

结果相同(有一些1e-16阶数值误差).

The results are the same (with a few numerical errors of order 1e-16).

np.power中还有哪些其他工作?此外,我本人如何找到此类问题的答案?

What additional work is done in np.power? Furthermore, how can I find an answer to these kind of questions myself?

推荐答案

Under the hood both expressions call the respective C functions pow or exp and log and running a profiling on those in C++, without any numpy code, gives:

pow      : 286 ms
exp(log) :  93 ms

这与numpy计时一致.因此,似乎主要的区别在于C函数powexp(log)慢.

This is consistent with the numpy timings. It thus seems like the primary difference is that the C function pow is slower than exp(log).

为什么?似乎部分原因是表达式并非对所有输入都是等效的.例如,对于负数a和整数bpower起作用,而exp(log)失败:

Why? It seems that part of the reson is that the expressions are not equivalent for all input. For example, with negative a and integer b, power works while exp(log) fails:

>>> np.power(-2, 2)
4
>>> np.exp(2 * np.log(-2))
nan

另一个例子是0 ** 0:

>>> np.power(0, 0)
1
>>> np.exp(0 * np.log(0))
nan

因此,exp(log)技巧仅适用于一部分输入,而power则适用于所有(有效)输入.

Hence, the exp(log) trick only works on a subset of inputs, while power works on all (valid) inputs.

除此之外,根据 IEEE 754标准,保证power可以提供完整的精度,而exp(log)可能会出现舍入错误.

In addition to this, power is guaranteed to give full precision according to the IEEE 754 standard, while exp(log) may suffer from rounding errors.

这篇关于np.power完成了哪些其他工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆