Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix Recursion Function overflow error?

This program is supposed to calculate the varying stopping power as a proton travels through aluminium for 20000 slices of 0.025µm of aluminium. The stopping power changes per slice, so the stopping power and subtraction of energy has to be calculated per slice.

I get a stack overflow error even after attempting to increase the recursive limit. Any assistance would be appreciated! distance(x,E,n) has the variables x which is the step, E which is the energy and n which is the stopping power. So distance(0,13000,0.13124) is the initial step, energy and stopping power.

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import sys

sys.setrecursionlimit(10**9)

def distance(x,E,n): 
    step = x + 1 
    if (step >= 20000):
        return E
    
    energy = E - 0.025 * 1/n #E - distance interval per step * stopping power
    stop = -0.0079199 + 0.040703 * energy**(-0.4) + 0.0022677 * energy**(0.25) + 0.000058309 * energy**(0.8) #1/stopping power
   
    return distance(step,energy,stop)

print(distance(0,13000,0.131234))

>Solution :

Recurring with a depth of 20000 is not reasonable. But as your recursive call comes at the very end, you can just convert this to an iterative solution — without recursion:

def distance(E, n):
    for _ in range(20000):
        E = E - 0.025 * 1/n #E - distance interval per step * stopping power
        n = -0.0079199 + 0.040703 * E**-0.4 + 0.0022677 * E**0.25 + 0.000058309 * E**0.8 #1/stopping power
    
    return E

print(distance(13000,0.131234))

I cannot judge if this formula is correct, but this is the translation of your code from a recursive approach to an iterative approach.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading