【问题标题】:IndexError trying to solve difference equations numerically in pythonIndexError 试图在 python 中以数值方式求解差分方程
【发布时间】: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


【解决方案1】:

我认为你的问题是你应该记住从 zero 开始的list 中任何元素的索引,最后一个元素的索引是 N - 1 其中N 是计数list.
中的元素 所以你应该在你的for循环中做这个改变:

for n in range(0, N):

另外,您对print 的使用应该反映了您list 中的数据。因此,您应该将 print 函数的参数固定为以下内容:

print(f"x[{n+1}] = {x[n+1]}")

进行这些更改后,您将得到以下结果:

x[1] = 1020.0
x[2] = 1040.4
x[3] = 1061.208
x[4] = 1082.43216
x[5] = 1104.0808032
x[6] = 1126.1624192640002
x[7] = 1148.68566764928
x[8] = 1171.6593810022657
x[9] = 1195.092568622311
x[10] = 1218.9944199947574

请注意,由于这行代码,您的 list 中有 N + 1 元素 not N 元素

x = (N+1)*[0]

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    修复索引

    您的索引范围与您在循环中使用它们的方式不一致。您可以使用以下两种可能的循环中的任何一种,但不要混合使用:

    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]
    

    优化:乘法而不是求幂

    请注意,计算指数 ** 总是比计算乘法 * 更昂贵;您可以使用递归公式稍微优化您的代码:

    for n in range(1, N+1):
        x[n] = r * x[n-1]
    
    for n in range(0, N):
        x[n+1] = r * x[n]
    

    使用库函数:itertoolsnumpypandas

    您所要求的称为几何级数。 Python 提供了多种计算几何级数的方法,而无需自己编写循环。

    例如:

    import itertools  # accumulate, repeat
    import operator   # mul
    def geometric_progression(x0, r, N):
        return list(itertools.accumulate(itertools.repeat(r,N), operator.mul, initial=x0))
    
    print(geometric_progression(1000, 1.2, 10))
    # [1000, 1200.0, 1440.0, 1728.0, 2073.6, 2488.3199999999997, 2985.9839999999995, 3583.180799999999, 4299.816959999999, 5159.780351999999, 6191.736422399998]
    

    【讨论】:

      【解决方案3】:

      你的数组的长度是 11,这意味着最后一个元素被 x[10] 访问。但是在循环中,当 n 为 10 时调用的值是 x[11],这使得它超出了范围。
      我不确定你的问题的限制,但如果你想访问x[11],请将数组的总大小更改为x = (N+2)*[0]

      输出

      x[1] = 1040.4
      x[2] = 1061.208
      x[3] = 1082.43216
      x[4] = 1104.0808032
      x[5] = 1126.1624192640002
      x[6] = 1148.68566764928
      x[7] = 1171.6593810022657
      x[8] = 1195.092568622311
      x[9] = 1218.9944199947574
      x[10] = 1243.3743083946524
      

      【讨论】:

        猜你喜欢
        • 2021-11-11
        • 1970-01-01
        • 2022-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多