Menu Close

Newton Raphson Method | Python

The Newton-Raphson method is an iterative method for finding the roots of a function f(x). It is based on the idea of linear approximation, and it can converge very quickly if the initial guess is close to the root.

Newton-Raphson method in Python for function f(x) = $x^{2}$ – 2:

				
					def newton_raphson(f, df, x0, tolerance, max_iterations):
  """
  Newton-Raphson method [By Bottom Science].
  
  Parameters:
  f - the function whose root we want to find
  df - the derivative of f
  x0 - the initial guess for the root
  tolerance - the maximum error allowed in the root
  max_iterations - the maximum number of iterations to perform
 
  """
  x = x0
  for i in range(max_iterations):
    x_new = x - f(x) / df(x)
    if abs(x_new - x) < tolerance:
      return x_new
    x = x_new
  raise Exception("Failed to converge after {} iterations".format(max_iterations))
 
#Your function   
def f(x):
  return x**2 - 2

#differentiation
def df(x):
  return 2*x

root = newton_raphson(f, df, 1.0, 1e-6, 100)
print(root)  # Output: 1.414213562373095


				
			

More Related Stuff