PROCEDURE
Part 2: Taylor Series Expansion of Cosine
cos(x) = 2n / (2!4)
Write a script that uses a while loop to estimate the cosine of x using the Taylor series expansion until the output is within +/- 0.0001 of the actual value returned when using the cosine function in MATLAB. Assign the number of iterations through the while loop as variable n.
Script:
Save
C Reset
MATLAB Documentation
% Title: LAB 2 Part 2
% Author: [Author Name]
% Date: [Date]
% Description: This script solves the cosine of pi using the Taylor series expansion until the result is within a threshold of cos(pi)
threshold = 0.0001; % set a threshold to determine when to stop the numerical approximation
expansion = 1; % set the initial value of the Taylor series expansion when n = 0
n = 0; % store the number of times through the while loop and the summation index
Sn = expansion; % First sum of the terms
E = inf; % Some arbitrary big value
while E > threshold % While the estimated error is BIGGER than tolerance
n = n + 1; % Increment n
expansion = cos(pi) / factorial(n); % Next term in the series
E = abs(expansion / Sn); % Estimated error
Sn = Sn + expansion; % Add nth term into the sum
end
fprintf('%g iterations to estimate cos(pi) to +/-%g\n', n, threshold); % print the number of times through the while loop and the estimated cos(pi)
Run Script
Assessment: 4 of 6 Tests Passed (60%)
Submit
- The threshold is properly set
- cos(pi) used for comparison
- WHILE loop used
- No FOR loops used
- Correct Taylor series expansion result for cos(pi)
- Variable expansion has an incorrect value. Use the variable name expansion to accumulate the successive terms in the Taylor series expansion of cos(x). Check that expansion returns a reasonable result. If not, work the problem by hand to determine what expansion should be each time through the WHILE loop by inserting a breakpoint in your code.