A05.m - Taylor Series Expansion (using a for loop)
% get info from user fprintf('Taylor series of cos(x) \n'); N = input('Enter the number of terms in the expansion: '); x = input('Enter the value of x to evaluate the function: '); % Taylor series of cos(x) approx = 0; for n=0:N-1 approx = approx + (-1)^n * x^(2*n) / factorial(2*n); end % Display the Taylor approximation and the resulting error to the command % window fprintf('\n') fprintf('Taylor series approximation = %.7g \n',approx) fprintf('actual value = %.7g \n',cos(x)); fprintf('error = %.3g \n',approx-cos(x));
The program approximates the function cos(x) using a Taylor series approximation. It first prompts the user to enter the number of terms in the Taylor series and the value of x.
The variable approx stores the Taylor series approximation. This variable is first initialized to 0. The for loop is used to calculate the successive terms in the expansion. Notice that the Matlab function factorial() is used to calculate the factorial of 2n in the expansion. The final result is displayed to the screen and compared with the more accurate value calculated by the Matlab function cos().
Try including 5 terms and evaluating the series at x=0.1 radians. Run the code a few more times. How large can you make x and still kep the error < 10^-3?