Python-运行程序时出现“索引错误”

时间:2018-10-21 01:52:57

标签: python python-3.x

我正在编写用于获取二阶导数的代码,但出现错误。就是说二阶导数方程行有问题。我不明白我要怎么做。

import numpy as np
import matplotlib.pyplot as plt

def d2(f,dx):
    df_dx = []
    for i in range(len(f)-1):
        df_dx.append(f[i+dx] - 2*f[i] + f[i-dx])/(dx*dx)

f = np.sin(np.linspace(0,5,50))
output = d2(f,0.1)
expected = np.cos(np.linspace(0,4.9,49))
diff = abs(output-expected)
plt.plot(diff)

IndexError:只有整数,切片(:),省略号(...),numpy.newaxis(None)和整数或布尔数组都是有效索引

1 个答案:

答案 0 :(得分:1)

您的代码有两个问题,一个是您试图使用浮点值对数组进行索引,另一个是您没有使用dx创建初始数据集。下面的代码解决了这两个问题:

import numpy as np
import matplotlib.pyplot as plt

def d2(f,dx):
    df_dx = []
    for i in range(1, len(f)-1): #start i at 1 so that i-1 is 0 on the first iteration
        df_dx.append((f[i+1] - 2*f[i] + f[i-1])/(dx*dx)) #add parenthesis around expression
    return df_dx

dx = 0.1 
x = np.arange(0, 5+dx, dx) # create an array that has a values spaced by dx
f = np.sin(x) 
output = d2(f,dx)
expected = -np.sin(x[1:-1]) #2nd derivative is missing first and last points from original array
diff = abs(output-expected)
plt.plot(x[1:-1], diff)