function newton_sec_fpos_fpoint; % p is the approximatoin of newtons's method % p_2, p_1 are the approximations of the secant method % q_2, q_1 are the approximations of the false position method % Two initial approximation for p_1=-0.5; p_2=0.1; % initial approximation of the secant method, p=0.5; %initial approximation of Newton's method, q_1=-0.5; q_2=0.1; %initial approximation of Method of False Position (root is inside [q_1, q_2]) q=0.5; %initial approximation of the fixed point method % n is the number of iterations n=60; % the same loop is for the both methods fprintf(1, '\n\n Compare the four methods \n'); for i=1:1:n p=p-f(p)/der_f(p); % Newton's p_secant=p_2-f(p_2)*(p_2-p_1)/(f(p_2)-f(p_1)); p_1=p_2; p_2=p_secant; %Secant method q_secant=q_2-f(q_2)*(q_2-q_1)/(f(q_2)-f(q_1)); % false position, root has to be always between q_2 and q_1 if f(q_secant)*f(q_2)<0 q_1=q_2; q_2=q_secant; %next point is computed from q_2 and q_secant else q_1=q_1; q_2=q_secant; %next point is computes from q_1 and q_secant end; q=g(q); % fixed point fprintf(1,'I: %3i Newton`s: %13.10f Secant: %13.10f F-Pos: %13.10f Fixed Point: %13.10f \n', i,p,p_secant,q_secant,q); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Add graphics, just to have a %% picture of the function near %% the initial approximation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% figure(1); %x=[2:0.01:4]; %plot(x,pi+0.5*sin(x/2)-x,3.6269420149,pi+0.5*sin(3.6269420149/2)-3.6269420149,'ro'); x=[-1:0.01:1]; %plot(x,x.^2,0,0,'ro'); plot(x,-x.^3-cos(x), -0.8654740331,-(-0.8654740331)^3-cos(-0.8654740331),'ro'); %plot(x,sign(x).*sqrt(abs(x)),0,0,'ro'); grid on %%% END OF GRAPHICS function y=g(x); % example 2.2#7 solve fixed point problem %y=pi+0.5*sin(x/2); % Another example: solve x^2=0 by fixed point, use g(x)=-x^2+x %y=-x^2+x; % One more: se example 2.3#2 solve by fixed point, use g(x)=-(cos(x))^(1/3) %y=-(cos(x))^(1/3); % a funny example: the function has infinite derivative at \$x=0\$, solve by fixed point, g(x)=-sign(x)*sqrt(abs(x))/5+x; %y=-sign(x)*sqrt(abs(x))/5+x; % y=x*x*sin(x); function y=f(x); % use example 2.2#7 solve as root finding problem by Newton's method %y=pi+0.5*sin(x/2)-x; % Another example: solve x^2=0 by Newton's method %y=x^2; % One more: se example 2.3#2 solve as root finding problem by Newton's method %y=-x^3-cos(x); % a funny example: the function has infinite derivative at \$x=0\$ %y=sign(x)*sqrt(abs(x)); % y=x*x*sin(x)-x; function y=der_f(x); % use example 2.2#7 solve as root finding problem by Newton's method %y=cos(x/2)/4-1; % Another example: solve x^2=0 by Newton's method %y=2*x; % One more: se example 2.3#2 solve as root finding problem by Newton's method %y=-3*x^2+sin(x); % a funny example: the function has infinite derivative at \$x=0\$ %y=1/(2*sqrt(abs(x))); % y=2*x*sin(x)+x*x*cos(x)-1;