% m18_prettynewton.m - Newton's method -- beautiful output, not beautiful program! function m18_prettynewton() close all set(gcf,'doublebuffer','on'); clear all global th fs = 'fontsize'; ms = 'markersize'; x = (-.8:.001:1.2); p = x.^5 -4*x.^4 + 5*x.^2 + x - 1; hold off plot(x,p,'b','linewidth',3), grid on axis([-.6 1.1 -1.5 2.2]) hold on plot([-2 2],[0 0],'-k','linewidth',2) set(gca,fs,18) x = .8; plot(x,0,'.k',ms,25) sh = text(-.442,1.7,'step 0',fs,22); clear th printroot(x,0); pause for step = 1:100 y = x^5 -4*x^4 + 5*x^2 + x - 1; plot([x x],[0 y],'--k','linewidth',1.8) plot(x,y,'.r',ms,25); pause yp = 5*x^4 - 16*x^3 + 10*x + 1; xnew = x - y/yp; plot([xnew x],[0 y],'r','linewidth',2) x = xnew; plot(x,0,'.k',ms,25) delete(sh); sh = text(-.442,1.7,['step ' int2str(step)],fs,22); printroot(x,step); pause end % printroot - print root in color function printroot(x,n); exact = 0.37339086218684; fs = 'fontsize'; len = 16; if abs(x-exact) > .01, s = num2str(x+1e-16,len); else s = num2str(x,len); end x = num2str(exact,len); col = 'black'; if exist('th'), delete(th), end th = zeros(len,1); for i = 1:len if s(i) ~= x(i), col = 'red'; end if i>2, th(i) = text(-.525+.058*i,1.3,s(i),fs,22,'color',col); elseif i==1 th(i) = text(-.5+.058*i,1.3,s(i),fs,22,'color',col); else th(i) = text(-.5+.058*i,1.3,s(i),fs,22,'color',col); end end end end