【问题标题】:function types in numbanumba 中的函数类型
【发布时间】:2017-06-07 13:24:59
【问题描述】:

目前在 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 年前。

【问题讨论】:

  • 您能否包括f 是什么(代码产生异常)和完整的回溯?

标签: python numba


【解决方案1】:

经过一些实验,我可以重现您的错误。在这种情况下,将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 中还有一个很好的闭包示例,其中还提到:

[...] 如果该函数是从另一个 jit 函数调用的,你应该 JIT 编译该函数。

【讨论】:

    猜你喜欢
    • 2022-07-09
    • 2022-06-17
    • 2021-07-12
    • 1970-01-01
    • 2021-03-04
    • 2022-01-22
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多