I need some help understanding this. I watched this YouTube video (https://www.youtube.com/watch?v=q5pwy1NZqbM) that shows how to graph derivative approximation errors on a loglog plot. I get what the final graph shows, but I'm not sure what is going on in the for loop of the script. Here is the script in full:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.exp(-x**2)
def f_diff(x):
return -2*x*np.exp(-x**2)
def center(x,h):
return(f(x+h)-f(x-h))/(2*h)
def forward(x,h):
return (f(x+h)-f(x))/h
def backward(x,h):
return (f(x)-f(x-h))/h
def third_approx(x,h):
return (2*f(x+h)+3*f(x)-6*f(x-h)+f(x-2*h))/(6*h)
x0 = 0.2
h_vector = [10**(-temp) for temp in np.arange(0,17,0.1)]
forward_result = np.zeros(len(h_vector))
center_result = np.zeros(len(h_vector))
backward_result = np.zeros(len(h_vector))
third_approx_result = np.zeros(len(h_vector))
true_result = np.zeros(len(h_vector))
for index, i in enumerate(h_vector):
forward_result[index] = forward(x0,i)
center_result[index] = center(x0,i)
backward_result[index] = backward(x0,i)
third_approx_result[index] = third_approx(x0,i)
true_result[index] = f_diff(x0)
plt.figure()
plt.loglog(h_vector, abs(forward_result-true_result),label ='Forward')
plt.loglog(h_vector, abs(center_result-true_result),label='Center')
plt.loglog(h_vector, abs(backward_result-true_result),label='Backward')
plt.loglog(h_vector, abs(third_approx_result-true_result),label='third_approx')
plt.grid()
plt.xlabel('h')
plt.ylabel('Absolute difference')
plt.legend()
plt.show()
The for loop is really confusing to me. This is what I'm used to:
x = np.arange(0,10,0.1) #could also use np.linspace
n = x.size
dx = 0.1
FD = np.zeros(n)
BD = np.zeros(n)
CD = np.zeros(n)
third = np.zeros(n)
exact = np.zeros(n)
for i in range(n):
FD[i] = forward(x[i],dx)
BD[i] = backward(x[i],dx)
CD[i] = center(x[i],dx)
third[i] = third_approx(x[i],dx)
exact[i] = df(dx)
I have never seen a for loop that says "for index, i in enumerate(x):" Why does it say "for index" rather than "for i in range"? What is enumerate? And how do I translate this into a for loop that I'm more familiar with?