我知道还有其他问题具有相同的错误消息,但是我已经看过这些并且不明白它如何适用于我目前的情况。所以我正在创建一个矩阵 u=np.zeros(shape=(nt,nx))
然后我还有两个数组 time=nt*[0]
和 middles=nx*[0]
这是我试图实现的关于绘制扩散方程的完整代码:
import numpy as np
import matplotlib.pyplot as plt
import math
D=1 #diffusion constant set equal to 1
C=1 #creation rate of neutrons, set equal to 1
L=math.pi
nx=101 #number of steps in x
nt=10002 #number of timesteps
dx=L/(nx-1) #step in x
dt=0.0001 # time step
Z=(D*dt)/(dx*dx) #constant for diffusion term
Z1=C*dt #constant for u term
x1=np.arange(-math.pi/2+0.03079992797, 0, 0.03079992797)
y=np.arange(0.06159985595,math.pi/2, 0.03079992797)
z = np.hstack((x1, y))
u=np.zeros(shape=(nt,nx))
time=nt*[0]
middles=nx*[0]
u[50,0]=1/dx #setting our delta function
for j in range(0,nt-1):
for i in range(2,nx-1):
u[j+1,i]=Z*(u[j,i+1]-2*u[j,i]+u[j,i-1])+Z1*u[j,i]+u[j,i]
u[j,1]=0
u[j,nx-1]=0
time[j]=dt*j
middles[j]=u[j,((nx-1)/2)]
if i==50 or i==100 or i==250 or i==500 or i==1000 or i==10000:
plt.plot(time,middles)
plt.title('Numerical Solution of the Diffusion Equation')
plt.xlabel('time')
plt.ylabel('middles')
plt.show()
however I keep getting this error message seen in the title only integers, slices (
: ), ellipsis (
… ), numpy.newaxis (
None ) and integer or boolean arrays are valid indices
The error message is in regards到 middles[j]=u[j,((nx-1)/2)]
行我正在尝试从 Matlabe 转换这段代码,如果这能解释一些事情的话
原文由 LOC12345 发布,翻译遵循 CC BY-SA 4.0 许可协议
当您不小心创建了一个
float
时,您经常会遇到此错误,其中包含您对索引值的计算之一。在这种情况下:
…将创建一个
float
当(nx-1)
是奇数时。所以你可以尝试:(我在这里使用
np.round
,这可能有点矫枉过正,但如果你开始除以 2 以外的数字,那么这种方法更有意义,因为它会向上或向下舍入int()
总是会打倒它。)Python 与 Matlab
需要注意两点: