2016-09-03 44 views
0

我得到下面的错误的代码低于管线11(其中b的定义)“列表”:类型错误:不支持的操作数类型(一个或多个),用于: - “INT”和绘图程序

不受支持的操作数类型为 - :'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() 

有人可以帮我吗?我不确定问题出在哪里,我对Python的科学用途也不太熟悉。谢谢!

+1

在哪里定义了?代码不完整。我敢打赌,'n'是一个使公式计算b无效的列表(代表int和列表的混合) –

+0

代码中的n表示体积分数,所以我希望它取0和1之间的所有值。但是当我说像浮点n =范围(0,1)它说无效的语法。 –

+0

0到1之间的所有值?那是无限的!和'range'只能用于整数。告诉我们你如何定义'n'。 –

回答

0

固定您的代码:

  • 上的每个值定义的范围内浮起的0和1
  • 呼叫B之间和构成阵列

代码:

#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() 
+0

非常感谢!有没有办法让n连续?或者这是否意味着在np.linspace函数中使步长非常小? –

+0

“让n是连续的”在纯粹的数学观点中是可能的,但在计算机中是不可能的:无限值意味着无限的计算时间,即使它是可能的也是如此......你必须减少这个步骤,直到你满意于绘制的图形。 –

相关问题