我是Python新手,感谢任何建设性的反馈 . 我的任务是使用ODEINT解决PDE,我的空间网格定义如下:
L = [8.0, 4.0, 8.0] # Lenght of spatial zones
dN = 1.0e2 # Number of grid points
N = [int(l*dN) for l in L] # Gives number of grid points over each spatial zone
通过使用ODEINT函数,我必须为我的解决方案定义一个零数组,以及一组时间点 . 我正在努力找出如何为数组写出正确的大小 . 我试过了:
dydt = np.zeros(shape=N) # For solution
t = np.linspace(0, 2, 2000) # for time
但是这给了我错误信息:
IndexError Traceback(最近一次调用最后一次)在()70 t = np.linspace(0,2,1N)71 ---> 72 U = odeint(数字,y0,t,args =(h,D1,D2,N) ))73 74 Fexit = U / Np
/Users/severinlangeberg/anaconda/lib/python3.5/site-packages/scipy/integrate/odepack.py in odeint(func,y0,t,args,Dfun,col_deriv,full_output,ml,mu,rtol,atol,tcrit ,h0,hmax,hmin,ixpr,mxstep,mxhnil,mxordn,mxords,printmessg)213 output = _odepack.odeint(func,y0,t,args,Dfun,col_deriv,ml,mu,214 full_output,rtol,atol,tcrit ,h0,hmax,hmin, - > 215 ixpr,mxstep,mxhnil,mxordn,mxords)216如果输出[-1] <0:217 warning_msg = _msgs [output [-1]]“运行full_output = 1得到量化信息 . “
在数字(y,t,h,D1,D2,N)39 40中对于[N [0] 1]中的i:#800 =特殊2,必须从N [1] ---> 41 dydt的开始[ i] = D2 *(-3 * y [i] 4 * y [i 1] - y [i 2] / h ** 2)#pluss 42 43 for i in range(N [0] 2,N [0 ] N [1] - 2):#从801到1197,或2到397
IndexError:索引801超出了轴0的大小为800的范围
Which seems to come from my loops:
# ODE setup
def numeric(y, t, h, D1, D2, N):
dydt = np.zeros((N))
# End grid points
dydt[0] = 0
dydt[-1] = 0
# Inner grid points
for i in range (1, N[0] - 2): # 1 to 797
dydt[i] = D1 * (y[i - 1] - 2*y[i]+ y[i + 1]) / h**2 # range i = j - 1
for i in [N[0] - 2]: # 798 = special 1
dydt[i] = D1 * (-3*y[i] - 4*y[i - 1] + y[i - 2]) / h**2 # minus
for i in [N[0] - 1]: # 799 = unknown, and last index in N[0]
dydt[i] = ((D1*(-3*y[i] + 4*y[i + 1] - y[i + 2])) - (D2*(-3*y[i] - 4*y[i - 1] + y[i - 2])))
for i in [N[0] + 1]: # 800 = special 2, must be from begining of N[1]
dydt[i] = D2 * (-3*y[i] + 4*y[i + 1] - y[i + 2] / h**2) # pluss
for i in range (N[0] + 2, N[0] + N[1] - 2): # from 801 to 1197, or 2 to 397
dydt[i] = D2 * (y[i - 1] - 2*y[i] + y[i + 1]) / h**2 # range
for i in [N[0] + N[1] - 1]: # at 1198, or 398 = special 3
dydt[i] = D2 * (-3*y[i] - 4*y[i - 1] + y[i - 2]) / h**2 # range
for i in [N[0] + N[1]]: # 1199, or 399 = unknown
dydt[i] = ((D1*(-3*y[i] + 4*y[i + 1] - y[i + 2])) - (D2*(-3*y[i] - 4*y[i - 1] + y[i - 2])))
for i in [N[0] + N[1] + 1]: # at 1200, or 1 = special 4
dydt[i] = D1 * (-3*y[i + 1] + 4*y[i + 2] - y[i + 3] / h**2) # pluss
for i in range (N[0] + N[1] + 2, N[0] + N[1] + N[2] - 1): # 1202 to 1999
dydt[i] = D1 * (y[i - 1] - 2*y[i]+ y[i + 1]) / h**2 # range
return dydt
2 回答
从快速看,似乎问题是for循环,而不是使用
for i in [N[0]]
,你确定它不是for i in range(N[0])
?for i in [N[0]]
相当多余,因为列表只包含一个元素,即 .N[0]
,所以当你试图寻找dydt[800]
<时,大小 800 的列表变得超出索引,因为最大索引是799
.像这样:
在这段代码中:
我总是800,所以它实际上与
dydt[ 800 ] = 0
相同 . 这比799大 .看起来你用错误的方式使用numpy数组 .
是的,在低级别它们代表连续的一系列整数或浮动的任何东西 . 但是在python级别上,np.array表示为数组数组 . (即第一个元素为3d矩阵
mtx = np.zeros(shape=[800,400,800]
在python中将是mtx[0][0][0]
)) .所以
for i in[N[0]]:
之后的所有代码都不起作用 . 它试图访问超出矩阵范围的子数组 .更新:
例如,你有3d矩阵(3x3x3)