Python Forum
Array assignments in a for loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Array assignments in a for loop (/thread-14307.html)



Array assignments in a for loop - mt_reilly - Nov-23-2018

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



RE: Array assignments in a for loop - wavic - Nov-23-2018

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])



RE: Array assignments in a for loop - ichabod801 - Nov-23-2018

I think OP means that yder and y_int give the same graph.