import numpy as np # %% Function f(x): def fun_f(x): f = (x + 1)*(x - 1) return f # %% Function df_dx: def fun_der_f(x): der_f = 2*x return der_f # %% Initialization: x_n = 2 f_tol = 0.001 n = 0 f_abs_n = np.inf n_max = 50 # %% Iterations with while loop: while (abs(fun_f(x_n)) > f_tol and (n < n_max)): x_np1 = x_n - fun_f(x_n)/fun_der_f(x_n) # Newton step x_s = x_np1 # Candidate of solution x_n = x_np1 # Index shift (preparing for next iter.) n += 1 # Updates number of iterations # %% Displaying results: print('x_s = ', x_s) print('n = ', n)