Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 三次迭代后散度处n阶导数导程的递归计算_Python_Math_Derivative - Fatal编程技术网

Python 三次迭代后散度处n阶导数导程的递归计算

Python 三次迭代后散度处n阶导数导程的递归计算,python,math,derivative,Python,Math,Derivative,我正在应用导数的形式定义,当它是一阶导数时,它可以很好地工作 h = 1e-05 #Some number ultimately close to 0 def derivative(f,x): return (f(x+h) - f(x)) / h #The formal definition 但是当推广n阶的公式时,由于某种原因,它在3次迭代中会出现奇怪的发散 from functools import lru_cache #For handling recursion @lru_c

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

h = 1e-05 #Some number ultimately close to 0
def derivative(f,x):
    return (f(x+h) - f(x)) / h #The formal definition
但是当推广n阶的公式时,由于某种原因,它在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,x,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#一些数字最终接近0
def衍生物(f,x):
return(f(x+h)-f(x))/h#形式定义
一个小词汇问题:这是而不是导数的正式定义。这是一个近似公式

用对称近似公式代替非对称近似公式 在大多数函数上,使用更对称的公式可以得到更好的结果:

h=1e-05#一些数字最终接近0
def衍生物(f,x):
返回(f(x+h)-f(x-h))/(2*h)#一个更好的近似值
使用相同的逻辑,您可以修改第n个衍生代码:

def(f,x,n):
如果n==1:
收益导数(f,x)
返回(n次导数(f,x+h,n-1)-n次导数(f,x-h,n-1))/(2*h)
或者反过来说:

def(f,x,n):
如果n==0:
返回f(x)
其他:
收益率导数(λy:导数(f,y),x,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个导数的通用公式。

如果使用调试器,它首先与预期的偏离在哪里?x**5的第4个导数是什么?你可以通过分析计算出来,检查你的结果。对于更大的
h
,效果很好。由于减去几乎相等的数字,你将陷入灾难。这更像是一个数值分析问题,而不是一个编程问题。在第4次迭代中使用更高的
h
似乎可以给出更准确的结果。使用多项式函数测试它时,它在大约相同的迭代中发散。由于
h
2*h
几乎是相同的数字,因此不会造成太大差异。像
sin
这样的周期函数似乎也在相同的迭代中发散。@Countour积分在
h
2*h
之间有一个因子2。这是两个不同的数字。