The Maclaurin series expansion for the cosine function up to
The Maclaurin series expansion for the cosine function up to some number of terms is given by cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8! - ..., x^n/ni, where x is the angle in radians and n\\ denotes the factorial of n. For example, the cosine approximations for one, three, and five terms are as follows: cos(x) = 1 cos(x) = 1 - x^2/2! + x^4/4! cos(x) = 1 + x^2/2! + x^4/4! - x^6/6! + x^8/8! Write a function cosineApprox that takes scalar input arguments x and the number of terms t, and returns the approximate value of cos(x). So, the function will be invoked as follows: approx = cosineApprox(x, t); Use a for loop in your code to calculate the cosine approximation up to the specified number of terms. Use the built-in MATLAB function factorial when computing the series expansion. Assume that x is in radians. Examples of correct function behavior for various values of x and t follow: >> x = 2*pi/3; >> actual = cos(x) actual = -0.5000 >> approx = cosineApprox(x, 2) approx = -1.1932 >> approx = cosineApprox(x, 5) approx = -0.4996 >> approx = cosineApprox(x, 10) approx =
Solution
% matlab code to approximate cosine value using maclaurian series
function approx = cosineApprox(x,t)
approx=1;
for i=1:1:t-1
addterm = (-1)^i*(x^(2*i))/factorial(2*i);
approx = approx + addterm;
end
end
x = 2*pi/3;
actual = cos(x);
disp(\"Original value: \");
disp(actual);
t = input(\"Enter number of terms: \");
approx = cosineApprox(x,t);
disp(\"Approximate Value: \");
disp(approx);
%{
output:
Original value:
-0.50000
Enter number of terms: 5
Approximate Value:
-0.49957
%}
