function Et = taylor_error_cjp(x,n) %TAYLOR_ERROR_CJP computes the expression in Equation 1 of HW1 % Et = TAYLOR_ERROR_CJP(X,N) computes Et as a function of the scalar % input X and the non-negative integer input N according to the equation % given in Task2 of HW1: Et is the true absolute error of an N-th order % Taylor series approximation of exp(x). If N is not an integer, the % function will truncate it to the nearest integer smaller than N. % % Inputs: % X: any scalar % N: the order of the Taylor approximation; must be a non-negative % integer % % Outputs: % Et: a scalar representing the true absolute error of the Taylor % series approximation % % Assumptions: % - this function only provides accurate results when the inputs X % and N are relatively small. %% %% ME 2016 Section %% Fall 2007 %% %% AUTHOR: Chris Paredis %% % start with some error checking % the input n must be a non-negative integer scalar % NOTE: it is important that the function stop executing when an error is % detected. The best way to accomplish this is by using the error() % function if length(n)>1 error('the input must be a scalar'); end if n<0 error('the input must be a non-negative integer'); end % make sure the input is an integer % NOTE: it is equally acceptable to generate an error if n is not an % integer n = floor(n); % this is a straightforward implementation of Equation 1 in HW1. It works % well for when x and n are relatively small, but runs into floating point % problems when x and n are large. taylor_sum = 1; power_term = 1; fact = 1; % factorial (abbreviated to avoid conflict with factorial() function for i=1:n % computing the power term and factorial based on the terms from the % previous iteration is slightly more efficient power_term = power_term * x; fact = fact * i; taylor_sum = taylor_sum + power_term/fact; end Et = exp(x) - taylor_sum; % An experienced Matlab programmer would probably avoid using the for-loop % as follows: (uncomment the lines below if you want to test this) %sum_range = 1:n; %Et = exp(x) - sum(x.^sum_range./factorial(sum_range)); % one can argue as to which of these implementations is most readable or % maintainable. The second implementation is somewhat more elegant and % concise; but for somebody who is not experienced using the colon operator % it can appear somewhat convoluted. % Both approaches are acceptable return;