Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why numpy.vectorize calls vectorized function more times than elements in the vector?

When we call vectorized function for some vector, for some reason it is called twice for the first vector element.
What is the reason, and can we get rid of this strange effect (e.g. when this function needs to have some side effect, e.g. counts some sum etc)

Example:

import numpy

@numpy.vectorize
def test(x):
    print(x)

test([1,2,3])

Result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1
1
2
3

numpy 1.26.4

>Solution :

This is well defined in the vectorize documentation:

If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs.

If you don’t want this, you can define otypes:

import numpy

def test(x):
    print(x)
    
test = numpy.vectorize(test, otypes=[float])
test([1,2,3])

1
2
3

In any case, be aware that vectorize is just a convenience around a python loop. If you need to have side effects you might rather want to use an explicit python loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading