In: Computer Science
Recall that the following Taylor series is used to approximate Cosine: cos(x) = ∑ (−1) nx 2n (2n)! ∞ n=0 You have been tasked with developing an m-file that allows other engineers to quickly determine the minimum n needed to reduce the truncation error below an error threshold. The truncation error is the absolute error between the approximation and MATLAB’s cos() function. You may want to Google the Taylor series to better your understanding of it. Your code should perform the following: 1. Ask the user to enter an error threshold value (scalar value) 2. Determine the number of terms (minimum n) needed so that the maximum truncation error for all values of x = −2π to 2π (increments of 0.01) is below the user error threshold. 3. Use fprintf to print the minimum n value, the mean truncation error and the maximum truncation error across all values of x. 4. Plot the truncation error against x. The following table can be used to check your answers.
Error threshold/ Minimum n value /Number of terms required
0.1 /8 /9
1e-5/ 12/ 13
1e-10 16 17
Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks.
Code:
clear;
threshold=input('Please give value of error threshold :');
totalValues=4*pi/0.01;
calculatedValues=zeros(1,round(totalValues));
x=-2*pi:0.01:2*pi;
originalValues=cos(x);
errors=zeros(1,round(totalValues));
maxi=1;
n=0;
while maxi>threshold
calculatedValues=zeros(1,round(totalValues));
for i = 0:n
calculatedValues=calculatedValues+((-1)^i/factorial(2*i))*(x.^(2*i));
end
n=n+1;
errors=abs(originalValues-calculatedValues);
maxi=max(errors);
end
fprintf("Threshold=%f, Value of n= %d, Terms required =
%d\n",threshold,n-1,n);
plot(x,errors),xlabel('x'),ylabel('error'),grid;
clear;
Output: