Week 5

Support Session 26.10.2020

In [8]:
# 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 
Iteration 1 :     9.51777272727
Iteration 2 :     7.28843611112
Iteration 3 :     5.62778443489
Iteration 4 :     4.40082353518
Iteration 5 :     3.51250399594
Iteration 6 :     2.9028885736
Iteration 7 :     2.5415560257
Iteration 8 :     2.39697856448
Iteration 9 :     2.37431810801
Iteration 10 :     2.37379929177
Iteration 11 :     2.37379902425

Root approx.: 2.3738