Ton*_*i04 1 arrays numpy python-2.7 python-3.x differential-equations
我在数值上为x网格和x向量以及时间网格设置了网格,但我还是为x(位置)设置了一个数组,该数组只能在0到20之间,并且t(时间)从0到因此,为了求解热方程,请先将其设为1000。但是每次例如要执行步骤10时,都会出现错误:
"Traceback (most recent call last):
File "/home/universe/Desktop/Python/Heat_1.py", line 33, in <module>
x[i] = a + i*h
IndexError: index 10 is out of bounds for axis 0 with size 10"
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
from math import sin,pi
import numpy
import numpy as np
#Constant variables
N = int(input("Number of intervals in x (<=20):"))
M = int(input("Number of time steps (<=1000):" ))
#Some initialised varibles
a = 0.0
b = 1.0
t_min = 0.0
t_max = 0.5
# Array Variables
x = np.linspace(a,b, M)
t = np.linspace(t_min, t_max, M)
#Some scalar variables
n = [] # the number of x-steps
i, s = [], [] # The position and time
# Get the number of x-steps to use
for n in range(0,N):
if n > 0 or n <= N:
continue
# Get the number of time steps to use
for m in range(0,M):
if m > 0 or n <= M:
continue
# Set up x-grid and x-vector
h =(b-a)/n
for i in range(0,N+1):
x[i] = a + i*h
# Set up time-grid
k = (t_max - t_min)/m
for s in range(0, M+1):
t[s] = t_min + k*s
print(x,t)
Run Code Online (Sandbox Code Playgroud)
您尝试索引超出范围:
for s in range(0, M+1):
t[s] = t_min + k*s
Run Code Online (Sandbox Code Playgroud)
改成:
for s in range(M):
t[s] = t_min + k*s
Run Code Online (Sandbox Code Playgroud)
而且有效。
您创建t的长度为M:
t = np.linspace(t_min, t_max, M)
Run Code Online (Sandbox Code Playgroud)
因此,您只能访问中的M元素t。
Python总是从零开始索引。因此:
for s in range(M):
Run Code Online (Sandbox Code Playgroud)
将执行M循环,而:
for s in range(0, M+1):
Run Code Online (Sandbox Code Playgroud)
会做M+1循环。