0

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.

omega
  • 40,311
  • 81
  • 251
  • 474
  • Not sure if this helps, but have you seen [this](http://adorio-research.org/wordpress/?p=6545)? – WGS Mar 14 '14 at 20:44
  • Duplicate on math.SE http://math.stackexchange.com/q/712524/115115, it would help to coordinate answers if you included hints about cross-postings in your post. By the way, the result you should be getting is 1.80106921195 – Lutz Lehmann Mar 16 '14 at 18:02

1 Answers1

0

Python is not good for recursive programming, being limited by default recursion depth as well as memory as it does not implement tail call recursion in favor of preserving stack traces.

You can identify your recursion limit with the sys module, mine is 1000:

>>> import sys
>>> sys.getrecursionlimit()
1000

You can also set your recursion limit, but that is inadvisable, because you may run out of memory, causing your system to crash:

sys.setrecursionlimit(limit)

You should consider reimplementing your function as a loop instead.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
  • See my answer at math.SE, recursion is the least of the problems, the whole philosophy of the implementation should be questioned. The accumulation of numerical noise in x alone prevents the termination of the algorithm for tol=1e-10. Depending on what role the recursion is really intended for, adaptation of the working tolerance or local step size control, one could end up, after straightening out the implementation, with a recursion level of 5, or of one million and larger. – Lutz Lehmann Mar 16 '14 at 18:17