[英]TypeError: unsupported operand type(s) for -: 'int' and 'list' for plotting program
I am getting the following error for the code below in line 11(where b is defined): 我在第11行(其中定义了b)下面的代码中收到以下错误:
unsupported operand type(s) for -: 'int' and 'list' -:'int'和'list'的不受支持的操作数类型
#Needed libraries
import numpy as np
import matplotlib.pyplot as mpl
#Defining given complex refractive indices
N1=complex(1.5,-7.6)
N2=complex(1.0,0.0)
#Defining the function that gives physically reasonable answer for effective medium
def B(x):
a=-2
b=(N1**2)*(2*(1-x)-x)+(N2**2)*(2*x-(1-x))
c=(N1**2)*(N2**2)
Nsq = (-b + np.sqrt(b**2-4*a*c))/(2*a)
return np.sqrt(Nsq)
#Plotting the function
G=B(n)
mpl.plot(n,G)
mpl.show()
Could someone help me out? 有人可以帮我吗? I'm not sure where the problem is and I'm not too experienced with scientific python usage. 我不确定问题出在哪里,对Python的科学用法也不太了解。 Thanks! 谢谢!
Fixed your code to: 将您的代码固定为:
B
on each value and compose an array 对每个值调用B
并组成一个数组 code: 码:
#Needed libraries
import numpy as np
import matplotlib.pyplot as mpl
#Defining given complex refractive indices
N1=complex(1.5,-7.6)
N2=complex(1.0,0.0)
#Defining the function that gives physically reasonable answer for effective medium
def B(x):
a=-2
b=(N1**2)*(2*(1-x)-x)+(N2**2)*(2*x-(1-x))
c=(N1**2)*(N2**2)
Nsq = (-b + np.sqrt(b**2-4*a*c))/(2*a)
return np.sqrt(Nsq)
nb_values = 10 # you can set it higher
n = np.linspace(0,1,nb_values+1)
# returns array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
#calling the function for each x in n, build an array from results
G=[B(x) for x in n]
#Plotting the function
mpl.plot(n,G)
mpl.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.