mercredi 18 mars 2020

Nested for loop. Save variable when condition is met

I'm a beginner and not very confortable with loops and therefore have run into an error I have been dealing with. I've attached my whole script, but it's about my nested for loop. My goal here is:

1) Loop through my inner loop n times with a value of "a".

2) Come back to the outer loop, choose a new value of a, and repeat.

I mean, the script runs. Might not be pretty, but the issue is that I want to store the last value of L for every a. Right now, I belive I am overwriting it with every outer loop.

How do I get Python to save the variable. I'm thinking something like:

if i=n:

L[i] = Ln[i]

but doesn't work for me. So, how do I make Python save a variable when a condition is met?


    import numpy as np
import matplotlib.pyplot as plt
from math import exp # exponential function
from math import *

n = 1000    #Iterations (1000 years)
t = np.ones(n)
t[0] = 0    #Time(0)
dt = 1      #Time step

    ## Parameters ##
d0 = 200     #d0 (Start height)
s = 0.014   #Slope
lambd = 300     #lambda
sigma = 10000   
xs = 40000  #x-coordinate of the "bump"
ac = 0.0005 #Accumulation
alfaf = 0.7 #Constant
alfam = 2 #Constant
eps = 1     #Constant
delta = 1.127 #Constant
c = 2.4 #Calving rate


    ## Grids ##
x = np.linspace(0,50000,5000) #My x grid
x[0] = 200              #Start position of glacier's head
L = np.ones(n)          #Glacier Length
#L[0] = 47000
L[0] = 14000
B = np.zeros(n)
Hf = np.ones(n)         #Defining vectors to loop through
F = np.ones(n)
dLdt = np.zeros(n)
ak = np.arange(0+2/n, 2+2/n, 2/n) #Store a as a vector

for a in np.arange(0+2/n, 2+2/n, 2/n):
    for i in range(1, n):
        t[i] = i
        x[i] = d0-s*L[i-1]+lambd*np.exp(-((L[i-1]-xs)/(sigma))**2) #Bed geometry
        B[i] = a*L[i-1]    #Surface mass balance
        Hf[i] = np.max([alfaf*np.sqrt(L[i-1]), -eps*delta*x[i-1]]) #Ice thickness at glacier front
        F[i] = np.min([0, c*x[i-1]*Hf[i-1]])    #Flux of ice at the glacier front
        dLdt[i] = (2*(B[i-1]+F[i-1]))/(3*alfam*np.sqrt(L[i-1])) #Differential equation
        L[i] = L[i-1] + 1*dLdt[i-1]     #Updating L with Eulers Method


Aucun commentaire:

Enregistrer un commentaire