I'm trying to implement code for Heun's method function. But I'm also doing it in the adaptive style. Regularly for say rectangle method, if you do adaptive style, you compare the area from a
to b
, with the sum of a
to the center of a
and b
and then from that center to b
. If its the same with a tolerance, then return the sum, if not, then recurse on both intervals.
This is what I got so far:
import math
def k(x,y):
return math.sin(x+y)
''' h is the step size '''
def Heun(f,x,y,h,end):
while x < end:
f0=f(x,y)
z=y+h*f0
x+=h
f1=f(x,z)
y+=h*0.5*(f0+f1)
return y
def AdaptDiff(diffF,f,x,y,h,end,tol):
if abs(1.-x/end) < tol:
return y
y1=diffF(f,x,y,1,x+h)
y_=diffF(f,x,y,1,x+h/2.)
y2=diffF(f,x+h/2.,y_,1,x+h)
if abs(1.-y1/y2) > tol:
return AdaptDiff(diffF,f,x+h/2.,y2,h/2.,end,tol)
return AdaptDiff(diffF,f,x+h,y1,h*2.,end,tol)
print AdaptDiff(Heun,k,0,1,1/2.,1,1e-10)
But I'm getting a maximum recursion depth exceeded error. Does anyone know whats wrong here? I should be getting 1.73513792333
.
Thanks.