TypeError:只有length1数组可以转换为Python标量,试图绘制对比度与exit ang

2024-10-03 09:11:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用以下代码创建绘图:

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行,错误如下:

^{pr2}$

我不确定问题是什么,因为问题在一个定义内,而不是定义在哪里被使用。对这个问题的任何帮助或见解都将是非常有帮助的,因为我花了几个小时思考它,尝试了不同的方法,但都没有效果。在


Tags: importreturndefpltcosa0arraydegrees
1条回答
网友
1楼 · 发布于 2024-10-03 09:11:02

您在theta_dependence(1, 1.52, thetain, thetaout)中传递thetaout来计算R,但是{}是一个空列表,如这里所定义:thetaout = array(stuff, float)。这就是厄洛尔留言的原因。虽然您在find_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和{}都是两个浮点数,plot取两个长度相同的iterable,因此将抛出一个错误。我猜你是想画出stuff和{}这两个长度相同的列表。我的建议是:

替换:

^{pr2}$

有:

plt.plot(stuff, things)

相关问题 更多 >