python - numba 中的函数类型

标签 python numba

目前在 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 fdoube(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/

相关文章:

python - numba 不接受 dtype=object 的 numpy 数组

python - 使用 numba 计算向量和矩阵行之间的余弦相似度

python - 从列表中提取数据

python - 将我的 Python 应用程序部署到 Heroku 会破坏 Heroku 的 Python 解释器

python - 如何消除 ☎ unicode?

python-3.x - numba jitclass 中的对象比较

Python/Numba - 自定义类对象作为输入类型

python - 如何获取python中的内置模块列表?

python - 找出给定日期是否属于当前周的 pythonic 方法是什么?

numpy - numba:就地排序数组