如何让我的代码生成一个值数组而不是一个值?

时间:2018-01-31 18:36:03

标签: python function graph

您好我已经编写了以下代码来生成菲涅耳衍射图案图:

import math
import cmath
import numpy as np
import matplotlib.pyplot as plt

lamda=0.00000005
k=(2*math.pi)/lamda
z=0.03
h=6.67e-34
c=3e8
e0=8.85e-12
E0=h*c/lamda
xp1=-1e-6
xp2=1e-6
t=1
N=100
y=0 
yp=1
yp1=-1e-6
yp2=1e-6
xp=0



def expfuncX(x,xp): #gives the x function to be integrated

    j=cmath.sqrt(-1)
    g=(k/2*z)*((x-xp)**2)    

    return cmath.cos(g)+cmath.sin(g)*j


def X(xp1,xp2,x,xp,f,N): #integrates the x function

    h=(xp2-xp1)/N
    ff=0
    xp=xp1
    for i in np.arange(1, N/2 +1): #summing odd order func terms

        ff+=4*f(x,xp)
        xp+=2*h

    xp=xp1+2*h
    for i in np.arange(2,N/2): #summing even order func terms

        ff+=2*f(x,xp)
        xp+=2*h

    integral= (h/3)*(ff+f(x, xp1)+f(x, xp2))    

    return integral




def expfuncXY(y,yp):  #gives the 2d func to be integrated

    j=cmath.sqrt(-1)
    g=(k/2*z)*((y-yp)**2)    

    return X(xp1,xp2,x,xp,expfuncX,N)*cmath.cos(g)+cmath.sin(g)*j    


def simpsonXY(yp1,yp2,y,yp,f,N): #integrates 2d function

    h=(yp2-yp1)/N
    ff=0
    yp=yp1
    for i in np.arange(1, N/2 +1): #summing odd order func terms

        ff+=4*f(y,yp)
        yp+=2*h

    yp=yp1+2*h
    for i in np.arange(2,N/2): #summing even order func terms

        ff+=2*f(y,yp)
        yp+=2*h

    integral= ((E0*k)/(2*(math.pi)*z))*(h/3)*(ff+f(y, yp1)+f(y, yp2))    

    return integral

print(simpsonXY(-1e-6,1e-6,1,0,expfuncXY,100))




NumPoints = 200
delta = 4.0*np.pi / (NumPoints - 1)
intensity = np.zeros( (NumPoints,NumPoints) )
for i in range(NumPoints):
    x = i * delta
for j in range(NumPoints):
    y = j * delta
intensity[i,j] =e0*c*((abs(simpsonXY(-1e-6,1e-6,1,0,expfuncXY,100))**2))
plt.imshow(intensity)
plt.show()

print(intensity)

但代码会生成this!

如何获取它以便打印出数组中的其余值而不仅仅是一个?我认为你需要定义一系列xvalues并将它们存储到函数中的x中,但是我不太清楚如何去做...

感谢

2 个答案:

答案 0 :(得分:0)

你的缩进有点古怪。你有:

intensity = np.zeros( (NumPoints,NumPoints) )
for i in range(NumPoints):
    x = i * delta
for j in range(NumPoints):
    y = j * delta
intensity[i,j] =e0*c*((abs(simpsonXY(-1e-6,1e-6,1,0,expfuncXY,100))**2))

当我认为你真正想要的是:

intensity = np.zeros( (NumPoints,NumPoints) )
for i in range(NumPoints):
    x = i * delta
    for j in range(NumPoints):
        y = j * delta
        intensity[i,j] =e0*c*((abs(simpsonXY(-1e-6,1e-6,1,0,expfuncXY,100))**2))

否则(在第一个代码块中)你只设置一个强度,即强度[NumPoints-1,NumPoints-1]

答案 1 :(得分:0)

使用meshgrid,这只是numpy.meshgrid

中的示例
import numpy as np
from matplotlib import pyplot as plt


x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)  

enter image description here