我正在尝试使用以下代码创建一个绘图:
from math import *
from numpy import array
import matplotlib.pyplot as plt
def contrast(R, a0):
C = (((R*a0)**2)-((1-2*R*a0)**2))/(((R*a0)**2)+((1-2*R*a0)**2))
return C
def theta_dependence(nin, nout, thetain, thetaout):
R = ((nin*cos(thetain)-nout*cos(thetaout))/(nin*cos(thetain)+nout*cos(thetaout)))**2
return R
def convert_degrees(degrees):
rtheta = (2*pi*degrees)/360.0
return rtheta
def find_thetaout(nout, thetain):
thetaout = asin(sin(thetain)/nout)
return thetaout
a0 = 1
thetain = 1E-16
stuff = []
thetaout = array(stuff, float)
things = []
contrast_var = array(things, float)
i=0
while (i<=360):
thetain = (convert_degrees(thetain))
stuff.append(find_thetaout(1.52, thetain))#1.52 is refractive index of glass
R = theta_dependence(1, 1.52, thetain, thetaout)
things.append(contrast(R, a0))
i += 0.1
thetain += 0.1
plt.figure(1)
plt.plot(thetaout, contrast_var)
plt.title("Contrast vs. Theta-Out")
plt.xlabel("Theta-Out (RAD)")
plt.ylabel("Contrast (ARB)")
plt.show()
问题似乎出现在第 12 行,并出现以下错误:
File "C:/Users/Nick/.spyder2-py3/interferometry computational.py", line 12, in theta_dependence
R = ((nin*cos(thetain)-nout*cos(thetaout2))/(nin*cos(thetain)+nout*cos(thetaout2)))**2
TypeError: only length-1 arrays can be converted to Python scalars
我不确定问题是什么,因为问题出在定义内,而不是使用定义的地方。对这个问题的任何帮助或见解都将非常有帮助,因为我花了几个小时思考它并尝试不同的事情无济于事。
您正在传递thetaout
theta_dependence(1, 1.52, thetain, thetaout)
来计算R
但thetaout
是一个空列表,如下所示:thetaout = array(stuff, float)
.这就是错误消息的原因。虽然你在函数find_thetaout
计算了thetaout
,但它是那里的局部变量,不会修改全局thetaout
。所以,这是我的建议:
在find_thetaout
函数中插入global thetaout
语句如下:
def find_thetaout(nout, thetain):
global thetaout
thetaout = asin(sin(thetain)/nout)
return thetaout
同样在语句plt.plot(thetaout, contrast_var)
中,thetaout
和contrast_var
都是两个浮点数,并且 plot 需要两个相同长度的迭代对象,因此会抛出错误。我猜你正在尝试绘制stuff
和things
这是两个相同长度的列表。我的建议:
取代:
plt.plot(thetaout, contrast_var)
跟:
plt.plot(stuff, things)