【发布时间】: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