2
first = np.random.rand(3,5)

def myfunc(z):
    if  z > 0.5:
        val =  z
    else:
        val =  0
    return val

second = np.vectorize(myfunc)(first)

def myfunc2(z):
    if  z < 0.5:
        val =  z
    else:
        val =  0
    return val

third = np.vectorize(myfunc2)(first)
print("first")
print(first)
print("second")
print(second)
print("third")
print(third)

Results are as follows :

first
[[0.35583844 0.89866138 0.06983657 0.04930049 0.3802954 ]
 [0.58969783 0.57097607 0.97938735 0.96245392 0.42167587]
 [0.17149216 0.6038677  0.56824784 0.84236898 0.5252295 ]]
second
[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]
third
[[0.35583844 0.         0.06983657 0.04930049 0.3802954 ]
 [0.         0.         0.         0.         0.42167587]
 [0.17149216 0.         0.         0.         0.        ]]

Why is the second array all zero? I am scratching my head over this unexpected result. I am not sure if I am doing something wrong or totally misunderstanding the vectorize function.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
user238607
  • 1,580
  • 3
  • 13
  • 18
  • 2
    Perhaps it infers the dtype from the first (or other test) output. Try changing `val = 0` to `val = 0.0` in both. – Andras Deak -- Слава Україні Mar 27 '20 at 18:42
  • 2
    @AndrasDeak : You are right. Changing the dtype, results in correct output. – user238607 Mar 27 '20 at 18:45
  • This is one of the pitfalls with using `np.vectorize`. It's so easy and tempting to use, that many users fail to read all the details. Such as the disclaimer about performance, or this bit about determining the return dtype. You should put more effort into solving this problem without using `np.vectorize`. – hpaulj Mar 27 '20 at 19:55
  • Similar question just a day ago: https://stackoverflow.com/questions/60876903/trivial-changes-in-numpy-vectorized-functions-domain-produce-huge-discrepancies – hpaulj Mar 27 '20 at 20:01

0 Answers0