function [] = chap_1_prob_1(nIter) % CHAP_1_PROB_1 - % % Written by: % -- % John L. Weatherwax 2005-06-02 % % email: wax@alum.mit.edu % % Please send comments and especially bug reports to the % above email address. % %----- xA = [ 0:0.1:1.0 ]; % Taylor series: % disp( 'Taylor series...' ); tic; for xi=1:length(xA) x = xA(xi); aatan = 0; for n=1:nIter, aatan = aatan - ((-1)^n)*(x^(2*n+1))/(2*n+1); end fprintf( 'x = %f; atan = %f; aatan = %f; abs acc = %f; rel acc = %f\n', xA(xi), ... atan(xA(xi)), aatan, ... abs(aatan-atan(xA(xi))), abs(aatan-atan(xA(xi)))/abs(atan(xA(xi))+eps) ); end tm = toc; fprintf( 'Approx. computation time = %f\n', tm/length(xA) ); disp( '------------------------------------------------------------------------' ); % Continued fraction (loop to create a string to pass to "eval"): % disp( 'Continued fraction...' ); tic; for xi=1:length(xA), x = xA(xi); str = '1/('; for n=1:nIter, term = [ num2str(2*n-1),'+(',num2str(n),'*x)^2' ]; str = [ str, term ]; if( n~=nIter ) str = [ str, '/(' ]; end end % Append enough closing parenthesis: for n=1:nIter, str = [ str, ')' ]; end % Perform the eval we have worked so hard for: aatan = x * eval( str ); fprintf( 'x = %f; atan = %f; aatan = %f; abs acc = %f; rel acc = %f\n', xA(xi), ... atan(xA(xi)), aatan, ... abs(aatan-atan(xA(xi))), abs(aatan-atan(xA(xi)))/abs(atan(xA(xi))+eps) ); end tm = toc; fprintf( 'Approx. computation time = %f\n', tm/length(xA) ); disp( '------------------------------------------------------------------------' ); % Rational function approx: % disp( 'Rational function approx...' ); tic; for xi=1:length(xA), % Initial conditions: P = [ 1 3 ]; Q = [ 1 3+xA(xi)^2 ]; for n=2:nIter, P = [ P, (2*n+1)*P(end) + (n^2)*xA(xi)*P(end-1) ]; Q = [ Q, (2*n+1)*Q(end) + (n^2)*xA(xi)*Q(end-1) ]; end aatan = xA(xi)*(P(end)/Q(end)); fprintf( 'x = %f; atan = %f; aatan = %f; abs acc = %f; rel acc = %f\n', xA(xi), ... atan(xA(xi)), aatan, ... abs(aatan-atan(xA(xi))), abs(aatan-atan(xA(xi)))/abs(atan(xA(xi))+eps) ); end tm = toc; fprintf( 'Approx. computation time = %f\n', tm/length(xA) ); disp( '------------------------------------------------------------------------' );