# Basic Newton-Raphson implementation
# e.g., solve: x**4 - 2*x**3 - 5 = 0
# derivative: 4*x**3 - 6*x**2
# guesses: x0 = 2.5 (good), x0 = 12.5 (poor)
import numpy as np
from math import *
newton2 = lambda x: x - (x**4-2*x**3-5)/(4*x**3-6*x**2)
nmax = 20 # max no of iterations permitted (can be changed)
iter = np.zeros(nmax) # create a numerical array to store the iterations
# Manual execution of the algorithm.....
#iter[0] = 12.5
#iter[1] = newton2(iter[0]); print('First iteration:', iter[1])
#iter[2] = newton2(iter[1]); print('Second iteration:', iter[2])
#iter[3] = newton2(iter[2]); print('Third...:', iter[3])
#iter[4] = newton2(iter[3]); print('Fourth...:', iter[4])
TOL = 1.0e-5 # precision (or tolerance)
#
# implementation using a for-loop with forced exit
iter[0] = 12.5 # initial guess
for i in range(1, nmax):
iter[i] = newton2(iter[i-1]) # Newton iteration
print('Iteration',i,': ',iter[i]) # display on the screen each iteration
if (fabs(iter[i] - iter[i-1]) < TOL): # stop the for-loop if precision is met
x0 = iter[i] # store the last iteration
break # terminate loop (prematurely)
print('\nRoot approx.:', round(x0,5)) # display the final result on the screen