Question

My following code is not producing a graph. When I run the program I receive the following error:

y3 = (-1)*sqrt(E_y3/v-E_y3)

ValueError: math domain error

To test the rest of the code I took that line out, thinking it would work minus that line. However, when I do that I receive a blank graph. My goal is to graph the y1 equation with values from 0 to 20, the y2 equation with even values from 0 to 20 and the y3 equation with odd values from 0 to 20.

from pylab import plot,show
from numpy import tan
from math import sqrt

w = 1
v = 20
m = 9.1094e-31
h = 6.62606957e-34

for E_y1 in range (21):
    y1 = tan(sqrt(w**2*m*E_y1/2*h**2))
for E_y2 in range (2,22,2):
    y2 = sqrt(v-E_y2/E_y2)
for E_y3 in range (1,21,2):
    y3 = (-1)*sqrt(E_y3/v-E_y3)

x1 = E_y1
x2 = E_y2
x3 = E_y3

plot(x1,y1)
plot(x2,y2)
plot(x3,y3)
show()
Was it helpful?

Solution

Within the for loops you assign single values to both E_y1 and y1, one after the other, each new value overriding the previous one. What you want is them representing ranges, or lists. The syntax looks like this:

E_y1 = range(21)
y1 = [tan(sqrt(w**2*m*x/2*h**2)) for x in E_y1]
x1 = E_y1
plot(x1,y1)
show()

Now Ey1 is a range of numbers, and y1 is a list.

And about that domain error: You are taking the square root of a negative number, so the problem is hardly surprising.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top