【问题标题】:Secant method using python使用python的正割方法
【发布时间】:2021-01-07 23:18:06
【问题描述】:

您将如何编写 python 代码以使用割线法找到非线性方程 fnon(x) = 0 的根?使用 secant(fnon,x0,x1,tol) 返回 x 作为计算的根, f 作为该根处的函数值。我的方法不起作用

【问题讨论】:

  • 您是否尝试过“手动”的简单示例?代码在哪一步产生不同的结果?你能看出为什么吗?然后你尝试了稍微复杂一点的例子吗?您是通过print 还是通过调试器完整地写出这些步骤?

标签: python math


【解决方案1】:

the website "Solving nonlinear algebraic equations" 提供的解决方案,它有额外的计算方法。

def secant(f, x0, x1, eps):
        f_x0 = f(x0)
        f_x1 = f(x1)
        iteration_counter = 0
        while abs(f_x1) > eps and iteration_counter < 100:
            try:
                denominator = float(f_x1 - f_x0)/(x1 - x0)
                x = x1 - float(f_x1)/denominator
            except ZeroDivisionError:
                print "Error! - denominator zero for x = ", x
                sys.exit(1)     # Abort with error
            x0 = x1
            x1 = x
            f_x0 = f_x1
            f_x1 = f(x1)
            iteration_counter += 1
        # Here, either a solution is found, or too many iterations
        if abs(f_x1) > eps:
            iteration_counter = -1
        return x, iteration_counter
    
    def f(x):
        return x**2 - 9
    
    x0 = 1000;   x1 = x0 - 1
    
    solution, no_iterations = secant(f, x0, x1, eps=1.0e-6)
    
    if no_iterations > 0:    # Solution found
        print "Number of function calls: %d" % (2 + no_iterations)
        print "A solution is: %f" % (solution)
    else:
        print "Solution not found!"

【讨论】:

    【解决方案2】:
    #example function
    import numpy as np
    fnon= lambda x: np.sin(x-np.pi)
    
    from scipy.optimize import root_scalar
    x0=0
    x1=5
    tol=1e-8
    x= root_scalar(fnon,method='secant',x0=x0,x1=x1,rtol=tol)
    print(x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多