使用@vectorize 装饰器创建Numpy的 universal 函数
Numba的vectorize允许Python函数将标量输入参数作为Numpy的ufunc使用,将纯Python函数编译成ufunc,使之速度与使用c编写的传统的ufunc函数一样。
vectorize()有两种操作模型:
主动,或者装饰期间编译:如果传递一个或者多个类型签名给装饰器,就将构建Numpy的universal function。后面将介绍使用装饰期间编译ufunc。
被动(惰性),或者调用期间编译:当没有提供任何签名,装饰器将提供一个Numba动态universal function(DUFunc),当一个未支持的新类型调用时,就动态编译一个新的内核,后面的“动态 universal functions”将详细介绍
如上所描述,如果传递一个签名给vectorizer()装饰器,函数将编译成一个numpy 的ufunc:
from numba import vectorize, float64
@vectorize([float64(float64, float64)])
def f(x, y):
return x + y
如果想传递多个签名,注意顺序,精度低的在前,高的在后,否则就会出奇怪的问题。例如int32就只能在int64之前。
@vectorize([int32(int32, int32),
int64(int64, int64),
float32(float32, float32),
float64(float64, float64)])
def f(x, y):
return x + y
如果给定的类型正确:
>>> a = np.arange(6)
>>> f(a, a)
array([ 0, 2, 4, 6, 8, 10])
>>> a = np.linspace(0, 1, 6)
>>> f(a, a)
array([ 0. , 0.4, 0.8, 1.2, 1.6, 2. ])
如果提供了不支持的类型:
>>> a = np.linspace(0, 1+1j, 6)
>>> f(a, a)
Traceback (most recent call last):
File "
TypeError: ufunc 'ufunc' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
vectorizer与jit装饰器的差别:numpy的ufunc自动加载其他特性,例如:reduction, accumulation or broadcasting: