【发布时间】:2021-11-14 01:26:48
【问题描述】:
我正在练习如何数值求解差分方程,但我经常遇到如下问题。
谁能帮我解决这个问题?
import numpy as np
N = 10
#alternative 1
#x = np.zeros(N+1, int) # Produces error IndexError: index 11 is out of bounds for axis 0 with size 11
#alternative 2
x = (N+1)*[0] # Produces error: IndexError: list assignment index out of range
x[0] = 1000
r = 1.02
for n in range(1, N+1):
x[n+1] = r**(n+1)*x[0]
print(f"x[{n}] = {x[n+1]}")
【问题讨论】:
-
您的索引范围与您在循环中使用它们的方式不一致;要么使用
for n in range(1, N+1): x[n] = r**n * x[0],要么使用for n in range(0, n): x[n+1] = r**(n+1) * x[0],但你写的是两者的不一致。 -
@Stef:啊哈!我检查了您提供的两个示例,它们按预期工作:-) 谢谢!
标签: python math index-error difference-equations