Newton

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

def f_prime(x):
    # Define the derivative of the equation
    return 2*x

def newton_raphson(initial_guess, tolerance, max_iterations):
    x = initial_guess
    iterations = 0
    
    while True:
        x_new = x - f(x) / f_prime(x)
        iterations += 1
        
        if abs(x_new - x) < tolerance or iterations >= max_iterations:
            break
        
        x = x_new
    
    if iterations >= max_iterations:
        print("Maximum iterations reached.")
    else:
        print("Root found:", x_new)
        print("Number of iterations:", iterations)

# Example usage
newton_raphson(initial_guess=3, tolerance=1e-6, max_iterations=100)
Share on Google Plus

About THE CHOOSEN

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment