Use MatLab Write a simple program to compare the secant meth
Use MatLab.
Write a simple program to compare the secant method with Newton\'s method for finding a root of each function.
a) x^3 - 3x + 1 with x0 = 2
b) x^3 - 2sin(x) with x0 = 1/2
Use the x1 value from Newton\'s method as the second starting point for the secant method. Print out each iteration for both methods.
Solution
a)
b)
%newton method
 x = 0.5;
 Tl = 0.0000001;
 count = 0;
 dx=1; %to execute while loop
 f=-0.83; % because f(0.5)=-0.83
 fprintf(\'step x dx f(x)\ \')
 fprintf(\'%3i %12.8f %12.8f %12.8f\ \',count,x,dx,f)
 xVec=x;fVec=f;
 while (dx > Tl || abs(f)>Tl)
 count = count + 1;
 fprime = 3*x^2 + 3;
 xnew = x - (f/fprime); % compute the new value of x
 dx=abs(x-xnew); % compute how much x has changed since last step
 x = xnew;
 f = x^3 - 2*sin(x); % compute the new value of f(x)
 fprintf(\'%3i %12.8f %12.8f %12.8f\ \',count,x,dx,f) %this will print value of x, dx and fx in every iteration
 %secant mathod
 x(1)=input(\'Enter first point of guess interval: \');
 x(2)=x %value from newton ethod
iteration=0;
 
 for i=3:1000
 x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) - f(x(i-2))));
 iteration=iteration+1;
 if abs((x(i)-x(i-1))/x(i))*100<n
 root=x(i)
 iteration=iteration
 break
 end
 end
 end

