EN VI

How to fix Recursion Function overflow error?

2024-03-16 02:30:06
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:

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.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login