首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IndexError:索引10超出了大小为10的轴0的边界

IndexError:索引10超出了大小为10的轴0的边界
EN

Stack Overflow用户
提问于 2016-04-08 07:35:50
回答 1查看 70.2K关注 0票数 10

我在数值上为x网格和x矢量以及时间网格设置网格,但我再次为x (位置)设置了一个数组,它应该只在0和20之间,t (时间)将从0到1000,因此为了求解热方程。但是每次我想要的时候,例如,我设置了10步的数量,我得到一个错误:

代码语言:javascript
复制
"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"

下面是我的代码:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-08 07:57:50

您尝试在范围之外建立索引:

代码语言:javascript
复制
for s in range(0, M+1):
    t[s] = t_min + k*s

更改为:

代码语言:javascript
复制
for s in range(M):
    t[s] = t_min + k*s

而且它是有效的。

创建长度为Mt

代码语言:javascript
复制
t = np.linspace(t_min, t_max, M) 

因此,您只能在t中访问M元素。

Python总是从零开始索引。因此:

代码语言:javascript
复制
for s in range(M):

将执行M循环,而:

代码语言:javascript
复制
for s in range(0, M+1):

将执行M+1循环。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36489042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档