secant

def f(x):
    # Define the equation you want to solve
    return x**2 - 4

def secant_method(x0, x1, tolerance, max_iterations):
    iterations = 0
    
    while True:
        x_next = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0))
        iterations += 1
        
        if abs(x_next - x1) < tolerance or iterations >= max_iterations:
            break
        
        x0, x1 = x1, x_next
    
    if iterations >= max_iterations:
        print("Maximum iterations reached.")
    else:
        print("Root found:", x_next)
        print("Number of iterations:", iterations)

# Example usage
secant_method(x0=3, x1=4, tolerance=1e-6, max_iterations=100)
Share on Google Plus

About THE CHOOSEN

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment