简体   繁体   中英

numpy.ndarray sent as argument doesn't need loop for iteration?

In this code np.linspace() assigns to inputs 200 evenly spaced numbers from -20 to 20.

This function works. What I am not understanding is how could it work. How can inputs be sent as an argument to output_function() without needing a loop to iterate over the numpy.ndarray?

def output_function(x):
    return 100 - x ** 2

inputs = np.linspace(-20, 20, 200)
plt.plot(inputs, output_function(inputs), 'b-')
plt.show()

numpy works by defining operations on vectors the way that you really want to work with them mathematically. So, I can do something like:

a = np.arange(10)
b = np.arange(10)
c = a + b

And it works as you might hope -- each element of a is added to the corresponding element of b and the result is stored in a new array c . If you want to know how numpy accomplishes this, it's all done via the magic methods in the python data model. Specifically in my example case, the __add__ method of numpy's ndarray would be overridden to provide the desired behavior.

What you want to use is numpy.vectorize which behaves similarly to the python builtin map .

Here is one way you can use numpy.vectorize :

outputs = (np.vectorize(output_function))(inputs)

You asked why it worked, it works because numpy arrays can perform operations on its array elements en masse, for example:

a = np.array([1,2,3,4]) # gives you a numpy array of 4 elements [1,2,3,4]
b = a - 1 # this operation on a numpy array will subtract 1 from every element resulting in the array [0,1,2,3]

Because of this property of numpy arrays you can perform certain operations on every element of a numpy array very quickly without using a loop (like what you would do if it were a regular python array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM