Numpy functions

Hi,
The first fucntion return the same array X without any change while the second one does take into account the numpy functions output. But I don’t figure out why the first one doesn’t change the X array.

import numpy as np

#1st solution

X = np.array([i/100 for i in range(100)])
def f_(X):
    for element in X:
        element=np.exp(np.sin(element)+np.cos(element))
    
    return X
   
print(f_(X))

#2nd solution

X = np.array([i/100 for i in range(100)])

def f_python(X):
    n=X.shape[0]
    for i in range(n):
            X[i]=np.exp(np.sin(X[i])+np.cos(X[i]))
    return X

print (f_python(X))

You are starting out with an array of 100 values.

In the first solution, you loop through the values in the array calculating a new value, but you never put that new value back into the array. See the example below. Here we create an array of three values. We index the first value in the array and add it to 2. The new value is 3, but the first value is left unchanged.

>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> new_value = a[0] + 2
>>> a
array([1, 2, 3])
>>> new_value
3

In order to change the value in the array, I need to set that index in the array to the new value:

>>> a[0] = new_value
>>> a
array([3, 2, 3])

Numerical values are immutable, so when you add one number to another (or apply any math to them), a new value is always returned.