非线性方程的根 (Python)

Root of non linear equation (Python)

我正在尝试获取一个函数的根,有人建议我尝试使用 Newthon 方法。

我已尝试执行以下操作:

def newton(f,Df,x0,epsilon,max_iter):
    '''Approximate solution of f(x)=0 by Newton's method.

    Parameters
    ----------
    f : function
        Function for which we are searching for a solution f(x)=0.
    Df : function
        Derivative of f(x).
    x0 : number
        Initial guess for a solution f(x)=0.
    epsilon : number
        Stopping criteria is abs(f(x)) < epsilon.
    max_iter : integer
        Maximum number of iterations of Newton's method.

    Returns
    -------
    xn : number
        Implement Newton's method: compute the linear approximation
        of f(x) at xn and find x intercept by the formula
            x = xn - f(xn)/Df(xn)
        Continue until abs(f(xn)) < epsilon and return xn.
        If Df(xn) == 0, return None. If the number of iterations
        exceeds max_iter, then return None.

    Examples
    --------
    >>> f = lambda x: x**2 - x - 1
    >>> Df = lambda x: 2*x - 1
    >>> newton(f,Df,1,1e-8,10)
    Found solution after 5 iterations.
    1.618033988749989
    '''
    xn = x0
    for n in range(0,max_iter):
        fxn = f(xn)
        if abs(fxn) < epsilon:
            print('Found solution after',n,'iterations.')
            return xn
        Dfxn = Df(xn)
        if Dfxn == 0:
            print('Zero derivative. No solution found.')
            return None
        xn = xn - fxn/Dfxn
    print('Exceeded maximum iterations. No solution found.')
    return None

f = lambda x: 1.03078 - (((x + 1.08804)**(23/252))*((2*x + 1.08804)**(37/252))*((3*x + 1.08804)**(19/126))) 

但我需要 Df 是 f 的一阶导数。我曾尝试使用 scipy 和 simpy 来获取它,但它是一种不同的数据类型,因此我正在使用的函数无法正常工作。

如果不是这样,谁能推荐一个不同的方法?

谢谢

我不确定计算导数的分析方法,但我认为近似值不会改变函数的结果。尝试更换 Dfxn = Df(xn) 和 Dfxn = (f(xn+delta)-f(xn))/delta 对于一些小三角洲。取决于您的功能的性质,但我认为小于 .1 应该没问题?