Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

math - Secant method using python

How would you write python code to find the root of the non linear equation fnon(x) = 0 using the secant method? Using secant(fnon,x0,x1,tol) returning x as the computed root and f as the function value at that root. My method isn't working


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A solution provided by the website "Solving nonlinear algebraic equations" which has additional ways to calculate it.

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!"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...