【问题标题】:Finite Difference Function Index Error:有限差分函数索引误差:
【发布时间】:2018-07-05 15:30:16
【问题描述】:

下面是有限差分法的一个函数,它是一种非常标准的计算导数的方法,给定一些函数 f(x)、一个网格 (np.linspace),以及每个部分之间的均匀距离网格 (h)。

遇到的问题是当我从 0,10 跨网格尝试已知函数(比如 x**2)时;我收到一个特定的错误。在代码之后,我将发布遇到的错误。

def finitedifference(f,x,h,n):
"""f : function you are attempting to differentiate.
   x : grid/domain with with you will differentiate.
   h : distance between uniform mesh.
   n : required for loop?"""
    df = np.zeros_like(x)
    for i in range(1,n):
        df[i] = (f[i+1]-f[i-1])/(2*h)
        #end_points
        df[0] = (f[1]-f[0])/h
        df[-1] = (f[-1]-f[-2])/h
    return print(df) 

我用什么:

f = x**3
x = np.linspace(0,10,11)
h = x[1] - x[0]
finitedifference(f,x,h,11)

我收到错误:

"IndexError: index 11 is out of bounds for axis 0 with size 11"

很遗憾,我不确定这意味着什么,所以也许可以澄清一下错误/补救措施?谢谢!

【问题讨论】:

    标签: python python-3.x indexing physics


    【解决方案1】:

    大小为 11 的数组(或列表)具有索引 0, 1, 2, ..., 10

    如果您对range(1, 11) 执行for 循环,它会遍历1, 2, 3, ..., 10。如果您随后尝试访问索引i+1,那么当i 到达10 时,您最终会出现在数组之外。

    另一方面,您遗漏了索引0。因此,您可能希望使用for i in range(n-1) 来确保您从顶部开始并保持在限制范围内。

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 2016-07-24
      • 2016-03-25
      • 1970-01-01
      • 2013-10-20
      • 2015-08-24
      • 2016-01-11
      • 2015-02-26
      • 1970-01-01
      相关资源
      最近更新 更多