Write a program to calculate the root of a nonlinear equation using Newton's method


Topic: Write a program to calculate the root of a nonlinear equation using Newton's method

Solution

class NewtonRaphsonSolver:
    def __init__(self, f, x, dfdx, min_tol=1e-3):
        self.func = f
        self.x = x
        self.derivative = dfdx
        self.min_tol = min_tol
    def calculate(self):
        func_val = self.func(self.x)
        iterations = 0
        while abs(func_val) > self.min_tol and iterations < 100:
            self.x = self.x - float(func_val) / self.derivative(self.x)
            func_val = self.func(self.x)
            iterations += 1
        if iterations <= 100:
            return self.x
        else:
            return None
def f(x):
    return x ** 4 - 16
def dfdx(x):
    return 4 * x ** 3
nrs = NewtonRaphsonSolver(f, 10, dfdx)
print(nrs.calculate())



List all Python Programs