使用有限差分法计算所提供函数的导数,Python
我可能应该首先说我对python比较陌生,但我以前用java和Matlab编写过代码 在python中,代码使用有限差分法计算所提供函数的导数,Python,python,function,reference,derivative,Python,Function,Reference,Derivative,我可能应该首先说我对python比较陌生,但我以前用java和Matlab编写过代码 在python中,代码 def func(f): return f g = func(cos) print(g(0)) 给出了结果 >1.0 asg现在被定义为余弦函数 我想写一个函数,用有限差分法计算任何函数的导数。该函数定义为 def derivator(f, h = 1e-8): 并希望实现以下目标: g = derivator(cos) print(g(0)) # should be
def func(f):
return f
g = func(cos)
print(g(0))
给出了结果
>1.0
asg
现在被定义为余弦函数
我想写一个函数,用有限差分法计算任何函数的导数。该函数定义为
def derivator(f, h = 1e-8):
并希望实现以下目标:
g = derivator(cos)
print(g(0)) # should be about 0
print(g(pi/2)) # should be about -1
现在我的导子函数是这样的
def derivator(f, h = 1e-8):
return (f(x+h/2)-f(x-h/2))/h
这肯定是错误的,但我不确定该如何修复它。有什么想法吗?如果定义了
x
,您当前的developerator()
函数(可能应称为differentior()
)将使用未定义的变量x
,并返回单个值--x
。您希望返回一个接受x值的函数。您可以定义内部函数并返回它:
def fprime(x):
return (f(x+h/2)-f(x-h/2))/h
return fprime
fprime = lambda x: (f(x+h/2)-f(x-h/2))/h # Don't do this!
return fprime
from math import cos, pi
def derivator(f, h = 1e-8):
def g(x):
return (f(x+h/2)-f(x-h/2))/h
return g
g = derivator(cos)
print(g(0)) # 0.0
print(g(pi/2)) # -0.999999993923
但是,由于您不在其他任何地方使用该函数,因此您可以使用该函数,该函数也较短:
return lambda x: (f(x+h/2)-f(x-h/2))/h
PEP 8中关于lambdas的唯一一点是,您不应该将lambda的结果赋给变量,然后返回它:
def fprime(x):
return (f(x+h/2)-f(x-h/2))/h
return fprime
fprime = lambda x: (f(x+h/2)-f(x-h/2))/h # Don't do this!
return fprime
from math import cos, pi
def derivator(f, h = 1e-8):
def g(x):
return (f(x+h/2)-f(x-h/2))/h
return g
g = derivator(cos)
print(g(0)) # 0.0
print(g(pi/2)) # -0.999999993923
在
派生函数中创建一个内部函数,并返回它:
def fprime(x):
return (f(x+h/2)-f(x-h/2))/h
return fprime
fprime = lambda x: (f(x+h/2)-f(x-h/2))/h # Don't do this!
return fprime
from math import cos, pi
def derivator(f, h = 1e-8):
def g(x):
return (f(x+h/2)-f(x-h/2))/h
return g
g = derivator(cos)
print(g(0)) # 0.0
print(g(pi/2)) # -0.999999993923
f
和h
将是返回函数关闭的一部分
还可以返回lambda表达式,使其成为一行:
return lambda x: (f(x+h/2)-f(x-h/2))/h
请注意,您可以使用计算导数。我可以问一下,您为什么使用(f(x+h/2)-f(x-h/2)/h
而不是(f(x+h)-f(x-h))/h
?我并不是说你错了,我的微积分只是有点生疏了。@JamesKelleher这是一个问题。一次运算使用的是稍微复杂一点,但它(通常,我认为)在这样近似时也稍微精确一点。@Theano:任务是编写一个函数来实现它,所以即使它是一种获得导数的迂回方法,我也要坚持它。@JamesKelleher:实际上这只是一个步长的问题,但是在你的建议中,一个人需要在分母中加上2*h,就像我们两人发布了不同的答案,然后看到了另一个人的答案,并将相同的内容添加到了我们自己的答案中。答案很好,谢谢!从未想过使用内部函数,很棒的东西。我应该看看兰姆达的表情,谢谢!从未想过使用内部函数,太棒了!我还应该读一下lambda函数。非常感谢你的帮助!