numba 中的函数类型 [英] function types in numba

查看:124
本文介绍了numba 中的函数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前在 numba 中处理高阶函数的最佳方法是什么?

我实施了正割方法:

def secant_method_curred (f):定义内部(x_minus1,x_0,continuous_tolerance):x_new = x_0x_old = x_minus1x_oldest = 无而 abs(x_new - x_old) >连续公差:x_oldest = x_oldx_old = x_newx_new = x_old - f(x_old)*((x_old-x_oldest)/(f(x_old)-f(x_oldest)))返回 x_new返回 numba.jit(nopython=False)(inner)

问题是没有办法告诉 numba fdoube(double),所以上面的代码用 nopython=True 中断>:

TypingError: Failed at nopython (nopython frontend)无类型的全局名称 'f'

在以前的版本中似乎有一个 FunctionType,但被删除/重命名:http://numba.pydata.org/numba-doc/0.8/types.html#functions

在这个页面,他们提到了一个叫做 numba.addressof() 的东西,它似乎有点帮助,但同样可以追溯到 4 年前.

解决方案

经过一些实验,我可以重现您的错误.在这种情况下,jit 传递给您的 secant_method_curred 的函数就足够了:

<预><代码>>>>从 numba 导入 njit>>>def func(x): # 一个示例函数...返回 x>>>p = secant_method_curried(njit(func)) # jitted 函数>>>p(1,2,3)2.0

也可以在传入njit(func)jit(func)时声明签名.

<小时>

文档 并且还提到:

<块引用>

[...] 如果该函数是从另一个 jitted 函数调用的,则应该对其进行 JIT 编译.

What is currently the best way of dealing with higher order functions in numba?

I implemented the 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)

The issue is that there's no way to tell numba that f is doube(double), so the above code breaks with nopython=True:

TypingError: Failed at nopython (nopython frontend)
Untyped global name 'f'

It seems like there was a FunctionType in previous versions, but got removed/renamed: http://numba.pydata.org/numba-doc/0.8/types.html#functions

On this page, they mention something called numba.addressof(), which seems kind of helpful, but again dates back 4 years.

解决方案

After a bit of experimentation I could reproduce your error. In the case it was enough to jit the function passed to your 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

You can also declare the signature when you pass in the njit(func) or jit(func).


There is also a good example of closures with numba in the documentation and it is also mentioned that:

[...] you should JIT-compile that function if it is called from another jitted function.

这篇关于numba 中的函数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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