function types in numba

2019-05-04 07:16发布

问题:

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.

回答1:

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.



标签: python numba