python中的有限差分近似

python中的有限差分近似,python,math,calculus,Python,Math,Calculus,我试图计算一个函数在x=0时的导数,但是我一直在用我尝试过的所有函数得到奇怪的答案。例如,对于f(x)=x**2,我得到所有点的导数都是2。我的有限差分系数是正确的,它是关于x的二阶导数的二阶精度 from numpy import * from matplotlib.pyplot import * def f1(x): return x**2 n = 100 # grid points x = zeros(n+1,dtype=float) # array to store val

我试图计算一个函数在x=0时的导数,但是我一直在用我尝试过的所有函数得到奇怪的答案。例如,对于f(x)=x**2,我得到所有点的导数都是2。我的有限差分系数是正确的,它是关于x的二阶导数的二阶精度

from numpy import *
from matplotlib.pyplot import *

def f1(x):
    return x**2

n = 100 # grid points

x = zeros(n+1,dtype=float) # array to store values of x
step = 0.02/float(n) # step size
f = zeros(n+1,dtype=float) # array to store values of f
df = zeros(n+1,dtype=float) # array to store values of calulated derivative

for i in range(0,n+1): # adds values to arrays for x and f(x)
    x[i] = -0.01 + float(i)*step
    f[i] = f1(x[i])

# have to calculate end points seperately using one sided form

df[0] = (f[2]-2*f[1]+f[0])/step**2
df[1] = (f[3]-2*f[2]+f[1])/step**2
df[n-1] = (f[n-1]-2*f[n-2]+f[n-3])/step**2
df[n] = (f[n]-2*f[n-1]+f[n-2])/step**2

for i in range(2,n-1): # add values to array for derivative
    df[i] = (f[i+1]-2*f[i]+f[i-1])/step**2

print df # returns an array full of 2...

x^2的二阶导数是常数2,二阶导数使用中心差商,正如分母中的平方所示。您的结果是绝对正确的,您的代码完全按照您的要求执行

要获得具有对称差商的一阶导数,请使用

df[i] = ( f[i+1] - f[i-1] ) / ( 2*step )

可获得函数f1点x处的一阶导数(对于f1(x)=x^2的情况):

def f1(x):

    return (x**2)

def derivative (f, x, step=0.0000000000001):

    return ((f(x+step)-f(x))/step)

希望对您有所帮助

您是否尝试过打印调试?(通过添加对中间值的
print
调用进行调试)@Danra我已经尝试过了,在计算df[I]时似乎出现了问题。我不知道为什么,因为实际的计算应该是正确的,我试过一个计算器,但我得到了相同的答案。数学是正确的,所以我不知道什么是错的。@Danra使用调试器是一个更好的想法。我确实是指二阶导数,但忘记了我指的是二阶导数,所以我检查所有的值都是错的。谢谢你给我指明了正确的方向。