Python Forum

Full Version: Array assignments in a for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am having difficulty trying to understand why two different expression in a for loop are producing the same result. In this case, I am doing numeric integration and differentiation as an exercise to learn some Python basics. But I am surprised to find that the produce the same values for different explicit assignments for y_int and yder. Inserted below is the Python code.

import numpy as np
import matplotlib.pyplot as plt

M = 101
x = np.linspace(-10, 10, num=M)
y = np.exp(-x**2)
y_int = np.zeros(M)
yder = y_int
plt.plot(x, y)
plt.show()
xs = range(x.size-1)
sm = 0
i = 0
for i in xs:
    sm = sm + 0.5*(y[i]+y[i+1])*(x[i+1]-x[i])
    y_int[i] = sm
    yder[i] = (y[i+1]-y[i])/(x[i+1]-x[i])
    
plt.plot(x[1:x.size-1], y_int[1:x.size-1])
plt.show()
    
for i in xs:
    yder[i] = (y[i+1]-y[i])/(x[i+1]-x[i])
    
print(sm)


plt.plot(x, yder)
plt.show()

del y_int
del yder
How does line 17 is different from line 23?

17.     yder[i] = (y[i+1]-y[i])/(x[i+1]-x[i])
23.     yder[i] = (y[i+1]-y[i])/(x[i+1]-x[i])
I think OP means that yder and y_int give the same graph.