2

Am looking to pass numpy arrays as arguments to a function? How is this done? Can i simply pass it like variables as shown below?

def force(x,y,z):
     for i in range(N):
        for j in range(i+1,N,1):
            xij=x[i]-x[j]
            yij=y[i]-y[j]
            zij=z[i]-z[j]
3
  • why do you rededeclare the arrays inisde the function ? You do pass them to the function and afterwards you redeclare it ? Commented Mar 1, 2016 at 7:51
  • sorry!!that was a mistake, i was going to show someother statements! I have changed it, now is the argument okay? Commented Mar 1, 2016 at 8:07
  • By the way, think about vectorizing your code. Commented Mar 1, 2016 at 22:36

3 Answers 3

11

Python is a dynamic language, meaning there is no type checking done during compilation. You can pass anything into a function.

Sign up to request clarification or add additional context in comments.

1 Comment

NumPy has special handling of their internal arrays of some sort (though I don't know details), would have been good to add to this.
3

I believe in newer version( I use 1.13) of numpy you can simply call the function by passing the numpy array to the fuction that you wrote for scalar type, it will automatically apply the function call to each element over the numpy array and return you another numpy array

>>> import numpy as np
>>> squarer = lambda t: t ** 2
>>> x = np.array([1, 2, 3, 4, 5])
>>> squarer(x)
array([ 1,  4,  9, 16, 25])

1 Comment

Hello, have you tried this with Python 3? I get scalars when I pass lists in.
0

In Python 3.11.6 you can pass a numpy array to a user-defined function. The function as applied across the array and the returned object is a numpy array:

>>> import numpy as np
>>> def f(x):
...     return 3*x**2 - 4*x + 5
... 
>>> f(3.0)
20.0
>>> xs = np.arange(-5,5,0.25)
>>> ys = f(xs)
>>> ys
array([100.    ,  91.6875,  83.75  ,  76.1875,  69.    ,  62.1875,
        55.75  ,  49.6875,  44.    ,  38.6875,  33.75  ,  29.1875,
        25.    ,  21.1875,  17.75  ,  14.6875,  12.    ,   9.6875,
         7.75  ,   6.1875,   5.    ,   4.1875,   3.75  ,   3.6875,
         4.    ,   4.6875,   5.75  ,   7.1875,   9.    ,  11.1875,
        13.75  ,  16.6875,  20.    ,  23.6875,  27.75  ,  32.1875,
        37.    ,  42.1875,  47.75  ,  53.6875])
>>> type(ys)
<class 'numpy.ndarray'>

# lifted from 
# https://github.com/karpathy/nn-zero-to-hero/blob/master/lectures/micrograd/micrograd_lecture_first_half_roughly.ipynb

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.