Search code examples
pythonfor-loopfor-in-loop

Calculate list result for recursive equations


I'm running into some trouble making a calculation over a list of elements for an equation which in result gives a list of elements for a second equation which influences the first equation. Equations are set as L1(i) = lamb1(i) * W1(i) and W1(i) = Q1(i-1)(R1/c1) + L1(i-1)(s1/c1) where the list values for lamb1 and Q1 are already known and initial list value for L1(0) = W1(0) = 0.

c1 = 1
R1 = 4.58
s1 = 8.41
lamb1 = [0.0, 0.0072, 0.0145, 0.0216, 0.0287, 0.0357, 0.0426, 0.0494, 0.0561, 0.0626, 0.0689]
Q1 = [0.0, 0.0612, 0.1219, 0.1821, 0.2417, 0.3006, 0.3586, 0.4158, 0.4719, 0.5268, 0.5802]

L1 = [0]
W1 = [0]

for i,j in zip(lamb1,W1):
    L_1 = i * j
    L1.append(L_1)

for i,j in zip(Q1,L1):
    W_1 = (R1/c1) * i + (s1/c1) * j
    W1.append(W_1)

When done like that the iteration for L1 stops at the second element and for W1 at the third element so I tried this:

for i,j in zip(lamb1,W1):
    L_1 = i * j
    print(L_1)
    L1.append(L_1)
    for i,j in zip(Q1,L1):
        W_1 = (R1/c1) * i + (s1/c1) * j
        W1.append(W_1)

But then the appending of L_1 and W_1 messes up the future results.

Any ideas of what is going wrong? Probably it is a basic mistake, but I've been scratching my head for a couple of days already.


Solution

  • Your mistake is that L1 and W1 should only be used to store results. You dont need them to do the calculation.

    This is my version. I used uppercase names for lists and lowercase for elements to avoid confusion (i and j are bad choice as it is usualy used for integers or counters and gives no clues to their signification in the formula).

    c1 = 1
    R1 = 4.58
    s1 = 8.41
    LAMB1 = [0.0, 0.0072, 0.0145, 0.0216, 0.0287, 0.0357, 0.0426, 0.0494, 0.0561, 0.0626, 0.0689]
    Q1 = [0.0, 0.0612, 0.1219, 0.1821, 0.2417, 0.3006, 0.3586, 0.4158, 0.4719, 0.5268, 0.5802]
    
    L1 = [0.]
    W1 = [0.]
    
    w1=0.
    l1=0.
    
    for lamb1,q1 in zip(LAMB1[1:],Q1[:-1]):
        
        # calculation
        w1 = (R1/c1) * q1 + (s1/c1) * l1
        l1 = w1 * lamb1
        
        
        # storage
        L1.append(l1)
        W1.append(w1)
    
    print(L1)
    print(W1)
    

    This gives me :

     [0.0, 0.0, 0.004064292, 0.012797626227552001, 0.027025241249665544, 0.047633377557075834, 0.07571488444386332, 0.11259001880174077, 0.1599549038606801, 0.21950832361591682, 0.29343194021091945]
    [0.0, 0.0, 0.280296, 0.59248269572, 0.9416460365737124, 1.3342682789096871, 1.7773447052550075, 2.2791501781728902, 2.8512460581226398, 3.5065227414683195, 4.258809001609861]