fonnesbeck
8/29/2013 - 5:26 PM

secant.py

from math import cos
def secant(fun, x0, x1, tol=1e-9, max_iter=100):
    
    iter = 0
    f0, f1 = fun(x0), fun(x1)
    
    while (abs(x1-x0) > tol) & (iter < max_iter):
        
        x_new = x1 - f1 * (x1 - x0) / (f1 - f0)
        
        x0, x1 = x1, x_new
        f0, f1 = f1, fun(x1)
        
        iter += 1
        
    if abs(x1 - x0) > tol:
        print("algorithm failed to converge")
        return
    print("algoritm converged in {0} iterations".format(iter))
    return x1
    
print(secant(lambda x: cos(x) - x, 2, 3))