I'm trying to use a while loop to determine the best value of h to minimise error in a Richardson extrapolation scheme, but I'm having trouble with the code. My script always outputs half the value of h that I input and displays no change in the relative error. The test function is: $$(x+2)e^x$$
Here is my script thus far:
f=(2+x)*np.exp(x)
x=2
h=0.4
n=4
def richardson(f,x,h,n):
'''Richardson extrapolation method for numerical calculation of second derivative '''
n=4
L=zeros(n,n)
for I in range(n):
L[I][0]=central_sec(function,x, 1/(2**(I+1)))
for j in range(1,n):
for i in range(n-j):
L[i][j]=((4**(j))*L[i+1][j-1]-L[i][j-1])/(4**(j)-1)
return L[0][n-1]
print('Approximation using Richardson Extrapolation is: ' + str(richardson(f, x, h, n)))
tol=1e-5
error=0.1
n=4
'''Calculating minimum error, relative error and best step size h'''
while(abs(error)>abs(tol)):
F=richardson(f, x, h, n)
h=h/2
error=abs((F-analytic(x))/analytic(x))
n=n+1
print("Function value is:", F, "Best h value is:", h, "Number of iterations:", n)
def relerror_richardson(f, x, h, n):
f=abs((richardson(f, x, h, n)-analytic(2))/analytic(2))
return f
print('Relative error is: ' + str(relerror_richardson(f, x, h, n)))
```