Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different results between python map and numpy vectorize

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]
like image 915
david Avatar asked Mar 21 '23 21:03

david


1 Answers

As the docstring says:

The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided by specifying the otypes argument.

you need to add a otypes argument:

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

or change return 0 to return 0.0 in basis2().

like image 150
HYRY Avatar answered Apr 06 '23 17:04

HYRY