Consider the function f(x) = x
Consider the function f(x) = x – xcosx, which has a root at x =0. Write a program to compare the rates of convergence of thebisection method (starting with a = -1, b = 1) and Newton’s method(starting with x = 1). Which method converges faster? Why?
Answer:
Solution:
Newton’s method converges fasterIn Bisection method more iteration then converge real root butNewton’s method less iteration and converge real roots
%% Bisection methodclcclear all%f= input(‘enter the function f \n’)f = @(x) [x-x*cos(x)];a=input(‘enter the first initial guesse point \n’)b=input(‘enter the second initial guesse point b \n’)%% provide the equation you want to solve with R.H.S = 0form.%% Write the L.H.S by using inline function%% Give initial guesses.%% Solves it by method of bisection.%% A very simple code. But may come handyif f(a)*f(b)>0 disp(‘Wrong choice Sp’)else p = (a + b)/2; err = abs(f(p)); while err > 1e-8 if f(a)*f(p)<0 b = p; else a =p; end p = (a + b)/2; err = abs(f(p)); endendout_put = p
%% matlab code ==newton Raphson methed
clcclear allf = @(x) [x-x*cos(x)]g = @(x) [1+x*sin(x)-cos(x)] %% diff of function f%g = input(‘enter the diff of function f = \n’)n = input(‘enter the number of iterations n = \n’)x0 = input(‘enter the inital approximation x0 \n’)for i=1:n %% increase iterations converge realroot x(1) = x0; x(i+1) = x(i) – (f(x(i))/g(x(i))); error_tolerance = abs(x(i) – x(i+1));endout_put= x(n)
***********************************************************