0
votes

Before I start to ask a question, I'm sorry not to be skilled in expressing my question in english and doing python...

To practice np.vectorize, I was writing some code.

def H(x):
if x == 0 : 
    return 0.5
elif x > 0:
    return 1
else :
    return 0

then, I define vH as vectorized function.

vH = np.vectorize(H)

and it works as I expect.

vH(0)
array(0.5)

however, when a input array has a negative number, it doesn't work for "zero".

a = np.array([ -1,  0. , 0, 1 ])
vH(a)
array([0, 0, 0, 1])              # I expect the result array([0, 0.5, 0.5, 1])

I try to find the reason and solution about this problem. I really don't know why it happen... Do I miss something???

please answer why it happen and how to fix it

thank you for reading this question!

1
Read what it says about the return value dtype, and the otypes parameter. vectorize appears to be simple, but is trickier than it appears. And it is never fast(er). - hpaulj

1 Answers

0
votes

The error comes from your returns : you only return numbers as ints, so vectorize understands that you only work with ints, so when you give 1 and 0, your vH only gives ints. What you should do is return floats instead, and maybe convert them after if you want.

def H(x):
    if x == 0:
        return 0.5
    elif x > 0:
        return 1.
    else :
        return 0.
vH = np.vectorize(H)
a = np.array([ -1,  0 , 0, 1 ])
vH(a)

For me, It returned :

array([0. , 0.5, 0.5, 1. ])