Python beginner here. I'm attempting to write a very simple function that calculates an approximate numerical derivative for an expression represented by an input array (or "List" here). I've written this function in matlab and it works fine, but python is confusing me by throwing an indexing error. Here's my attempt:
def diffr(h, myList = []):
d = [];
for n in myList:
if myList.index(n) > 0:
print(myList.index(n))
d_elem = (myList[n] - myList[n-1])/h
d.append(d_elem)
return d
The idea is to subtract myList(n-1)
from myList(n)
and divide by h
, and go down the list. I realize that on the first iteration, myList(n-1)
will be out of bounds, which is why i put the if clause to check for that condition. But python throws this error after only 5 iterations:
IndexError: list index out of range
pointed at the d_elem
line. Funny thing is when i comment out that line and just have the loop print the indices, it goes through the loop just fine. What gives? thanks in advance.