Noah Huerta
Noah Huerta

Reputation: 1

How to fix for loop for a list

I am trying to create y as an array to create a function iterating through zeta which is dependent upon E all using a for loop. However the values are not being added to the list.

I have also tried defining the variables and the mathematical function as two different coding functions

screenshot

import cmath

import matplotlib.pyplot as plt

a = 2*10**-15
Vo = 83*10**6
m = 1.6726*10**(-27)
pi = cmath.pi
E = []
E.append(-83*10**6)
hbar = 6.62607015*10**(-34)/ pi
K = 16.032280*10**6
y = []
y.append(51311.18131)

def variables(y, E):
    for i in range(1, 83, 1):
        alpha = cmath.sqrt(2*m*(E[i-1]+Vo)/(hbar**2))
        zeta = alpha*a
        eta = cmath.sqrt(k - zeta**2)
        y[i] = zeta*cmath.tan(zeta) - eta
        E[i] = E[i-1] + 1
    return y, E
print('E = ', E, 'Y = ', y)
plt.plot(E, y)

The program as of now should graph y values as a function of Zeta which is changing with energy.

Upvotes: 0

Views: 53

Answers (2)

John
John

Reputation: 13699

In addition to @Barmar's answer your k variable needs to be K (upper case).

import cmath

import matplotlib.pyplot as plt

a = 2*10**-15
Vo = 83*10**6
m = 1.6726*10**(-27)
pi = cmath.pi
E = [0] * 83
E.append(-83*10**6)
hbar = 6.62607015*10**(-34)/ pi
K = 16.032280*10**6
y = [0] * 83
y.append(51311.18131)

for i in range(1, 83, 1):
    alpha = cmath.sqrt(2*m*(E[i-1]+Vo)/(hbar**2))
    zeta = alpha*a
    eta = cmath.sqrt(K - zeta**2)
    y[i] = zeta*cmath.tan(zeta) - eta
    E[i] = E[i-1] + 1

print('E = ', E, 'Y = ', y)
plt.plot(E, y)

Also it is not required to use append as sometimes append doesn't always work well with calculated index lookups. It might be better for you to initialize the y and E lists to be the length of your loop first.

Upvotes: 0

Barmar
Barmar

Reputation: 781789

You don't need the loop to be in a function, just put it at the top-level of the script. And use y.append() and E.append() to add to those lists.

for i in range(1, 83):
    alpha = cmath.sqrt(2*m*(E[i-1]+Vo)/(hbar**2))
    zeta = alpha*a
    eta = cmath.sqrt(k - zeta**2)
    y.append(zeta*cmath.tan(zeta) - eta)
    E.append(E[i-1] + 1)

Upvotes: 1

Related Questions