目前在 numba 中处理高阶函数的最佳方法是什么?
我实现了 secant method :
def secant_method_curried (f):
def inner (x_minus1, x_0, consecutive_tolerance):
x_new = x_0
x_old = x_minus1
x_oldest = None
while abs(x_new - x_old) > consecutive_tolerance:
x_oldest = x_old
x_old = x_new
x_new = x_old - f(x_old)*((x_old-x_oldest)/(f(x_old)-f(x_oldest)))
return x_new
return numba.jit(nopython=False)(inner)
问题是没有办法告诉 numba f
是 doube(double)
,所以上面的代码用 nopython=True
:
TypingError: Failed at nopython (nopython frontend)
Untyped global name 'f'
在以前的版本中似乎有一个 FunctionType,但被删除/重命名:http://numba.pydata.org/numba-doc/0.8/types.html#functions
On this page ,他们提到了一个叫做 numba.addressof() 的东西,这似乎很有帮助,但同样可以追溯到 4 年前。
最佳答案
经过一些实验,我可以重现您的错误。在这种情况下,jit
传递给您的 secant_method_curried
的函数就足够了:
>>> from numba import njit
>>> def func(x): # an example function
... return x
>>> p = secant_method_curried(njit(func)) # jitted the function
>>> p(1,2,3)
2.0
你也可以在传入njit(func)
或jit(func)
时声明签名。
在 documentation 中还有一个很好的 numba 闭包示例。并且还提到:
[...] you should JIT-compile that function if it is called from another jitted function.
关于python - numba 中的函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41799508/