4

My understanding is that (one use of) numpy's vectorize allows me to send an array to a function that normally only takes scalars, instead of using the built in map function (in combination with a lambda function or the like). However, under the following scenario I am getting different results when I use map vs numpy.vectorize and I can't seem to figure out why.

import numpy as np

def basis2(dim, k, x):
    y = np.array([-0.2, -0.13, -0.06, 0, 0.02, 0.06, 0.15, 0.3, 0.8,
                  1.6, 3.1, 6.1, 10.1, 15.1, 23.1, 30.1, 35.0, 40.0, 45.0, 50.0, 55.0])

    if x < y[k] or x > y[k + dim + 1]:
        return 0

    elif dim != 0:
        ret = ((x - y[k]) / (y[k + dim] - y[k])) * basis2(dim - 1, k, x) + (
            (y[k + dim + 1] - x) / (y[k + dim + 1] - y[k + 1])) * basis2(dim - 1, k + 1, x)
        return ret

    else:
        return 1.0

w = np.array([20.0, 23.1, 30.0])
func = lambda x: basis2(3, 14, x)
vec = map(func, w)

func2 = np.vectorize(basis2)
vec2 = func2(3, 14, w)

print vec  # = [0, 0.0, 0.23335417007039491]
print vec2  # = [0 0 0]
4

1 回答 1

7

正如文档字符串所说:

的输出的数据类型vectorized是通过使用输入的第一个元素调用函数来确定的。这可以通过指定otypes参数来避免。

您需要添加一个otypes参数:

func2 = np.vectorize(basis2, otypes="d")

或更改return 0return 0.0in basis2()

于 2013-10-28T03:07:37.257 回答