For loop

def f(x):
return np.exp(x)
n = 4
h = [0.01,0.02,0.05,0.10]

def forwardD(x):
for i in range(n):
fdashf = [ ]
fdashf = np.append(f(x+h[0:]) - f(x))/h[0:]
return fdashf
DerivativeF = forwardD

Hey guy’s Im trying execute a forward difference for the function e^x for multiple values of h. However I would like to avoid having to hard code each calculation and would like to write it using a efficient for loop. The code above is what I have done so far, when i run the code it runs fine however, when try to pass forwardD(2) or any value of x into the console, I get this error:

File “C:\Users\linnt\Documents\GitHub\ICT’s\MECH3750\Question2.py”, line 65, in forwardD
fdashf = np.append(f(x+h[0:]) - f(x))/h[0:]

TypeError: unsupported operand type(s) for +: ‘int’ and ‘list’
Does anyone know how to fix this error or give me a better way to execute my task?

It doesn’t appear you posted your function call, but it looks like you passed an integer to DerivativeF meaning you end up trying to add a list to an integer, x + h[0:]

I’d guess you’d want to use a single element from the list and loop through it using i, but I could be very off there.

I’m unsure what np is, though I’ll venture a guess it’s from the numpy library (which I know next to nothing about). That being said, someone else could probably give more detail on how to fix your problem.