【问题标题】:IndexError: index 10 is out of bounds for axis 0 with size 10IndexError:索引 10 超出轴 0 的范围,大小为 10
【发布时间】:2016-07-29 02:15:22
【问题描述】:

我在数字上为 x-grid 和 x-vector 以及时间网格设置了一个网格,但我再次为 x(位置)设置了一个数组,它应该只在 0 到 20 和 @987654322 之间@(时间)将从 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"

这是我的代码:

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)

【问题讨论】:

  • 数组索引为零,即 0-9

标签: arrays python-2.7 python-3.x numpy differential-equations


【解决方案1】:

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

for s in range(0, M+1):
    t[s] = t_min + k*s

改为:

for s in range(M):
    t[s] = t_min + k*s

而且它有效。

你创建t,长度为M:

t = np.linspace(t_min, t_max, M) 

所以你只能访问t中的M元素。

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

for s in range(M):

会做M循环,而:

for s in range(0, M+1):

会做M+1循环。

【讨论】:

  • 是的,它现在确实在工作,但是 x 的值应该被分成等距的间隔,从:a = 0.0 到 b=1.0,它似乎没有给我我想要的值,因为它给出的值超过 1
  • 谢谢,因为我现在可以正常工作和运行@MikeMuller
  • 很好,它有帮助。顺便说一句,如果它解决了你的问题,你可以accept 一个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 2020-04-24
  • 2021-07-17
  • 2021-05-24
  • 2018-07-23
  • 2019-03-01
  • 2021-08-23
相关资源
最近更新 更多