微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

3次迭代后,N阶导数在散度处的递归计算

如何解决3次迭代后,N阶导数在散度处的递归计算

我正在应用导数的形式定义,当它是一阶时,它可以很好地工作

h = 1e-05 #Some number ultimately close to 0
def derivative(f,x):
    return (f(x+h) - f(x)) / h #The formal deFinition

但是当概括 Nth 阶的公式时,由于某种原因,它奇怪地在3次迭代中发生了分歧

from functools import lru_cache #For handling recursion

@lru_cache(maxsize=200)
def NthDerivative(f,x,n):
    if n==1:
        return derivative(f,x)
    return ( NthDerivative(f,x+h,n-1) - NthDerivative(f,n-1) ) / h

for i in range(1,100):
   print(NthDerivative(lambda x : x**5,1,i))

在迭代次数超过3之前,这完全可以正常工作

5.000100001040231 #1st order
20.00059895479467 #2nd order
60.17408793468348 #3rd order
-44408.92098500626 #4th order (Here it happens)
11102230246.251564
-2220446049250312.5
3.5527136788004995e+20
-4.440892098500624e+25

我不明白这里出了什么问题,是因为一些小的浮点数错误吗? 当然,这不仅发生在此特定功能上,我尝试过的所有传送都在 3 处发生了分歧。

这是怎么了?

解决方法

h = 1e-05 #Some number ultimately close to 0
def derivative(f,x):
    return (f(x+h) - f(x)) / h #The formal definition

一个小的词汇问题:这不是衍生产品的正式定义。这是一个近似公式。

使用对称逼近公式代替非对称公式

使用更对称的公式可以为大多数函数提供更好的结果:

h = 1e-05 #Some number ultimately close to 0
def derivative(f,x):
    return (f(x+h) - f(x-h)) / (2*h) #A better approximation

使用相同的逻辑,您可以修改第N个派生代码:

def NthDerivative(f,x,n):
    if n==1:
        return derivative(f,x)
    return ( NthDerivative(f,x+h,n-1) - NthDerivative(f,x-h,n-1) ) / (2*h)

反之亦然:

def NthDerivative(f,n):
    if n==0:
        return f(x)
    else:
        return NthDerivative(lambda y: derivative(f,y),n-1)

我无法再现您的不同结果,因为我不知道您要区分哪些功能。

直接编写高阶导数的公式

代替使用递归来逼近 ...的近似值的导数的近似值... ,您可以直接为高阶导数编写一个近似公式。

例如,编写f'(x) = (f(x+h) - f(x-h)) / (2*h)f''(x) = (f'(x+h) - f'(x-h)) / (2*h)并在f'(y)中发展f''(x)的出现,您将得到:

f''(x) = (f(x+2*h) - 2 * f(x) + f(x-2*h)) / (4 * h**2)

以这种方式编写公式比调用递归函数更有效,因为这样可以减少对f的求值。

可以为f'''f''''等获得相似的公式。

最后,您可以尝试找到第N个导数的通用公式。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。