Text: MATLAB programming with repetition structures
The cosine function can be evaluated by the following infinite series, where x is in radians:
cos(x) = 1 - (x^2/2!) + (x^4/4!) - (x^6/6!) + ...
Here, the 2k factorial, (2k)! = 1 * 2 * 3 * ... * 2k, can be computed with MATLAB's function factorial(). For example, 6! = 1 * 2 * 3 * 4 * 5 * 6 is computed with "factorial(6)" in MATLAB.
Step 1: Create an M-file with a repetition (i.e., for-loop) structure based on the incomplete sample code below to compute and display the value of cos(x) as terms are added in its series up to a maximum number of terms. Specifically, compute and display values for each of these truncated series:
cos(x) = 1 for k = 0 (giving k + 1 = 1 term),
cos(x) = 1 - (x^2/2!) for k = 1 (giving k + 1 = 2 terms),
cos(x) = 1 - (x^2/2!) + (x^4/4!) for k = 2 (giving k + 1 = 3 terms),
cos(x) = 1 - (x^2/2!) + (x^4/4!) - (x^6/6!) for k = 3 (giving k + 1 = 4 terms),
...
up to a user-defined maximum number of terms. For each number of terms, compute and display the absolute value of the true relative error, εt, as defined by:
εt = 100% * (true value - approximation) / true value
Step 3: For nine terms in the series, i.e., k = 8, test the M-file with the data in the following table while stating the missing values for cos(x) and the percent error:
x | cos(x) | Error%
0.2 | 0.9801 | 0
0.7 | |
1.25 | |
clc; clear all;
x = input('Enter the value of x in radians: ');
cos_x = 0;
for k = 0:8
disp(['With ', num2str(k+1), ' terms, we have '])
true_relative_error = ?
end