cos taylor series in matlab

To evaluate the cosine of an angle using the Taylor series in Matlab, we can use the built-in cos function in a loop to calculate the series expansion of cosine. The general formula for the Taylor series expansion of cosine is given as:

cos taylor series formula

Here is the Matlab code to evaluate the cosine function using its Taylor series expansion:

main.m
function cosVal = cos_taylor(x, n)
% Evaluate cosine(x) using its Taylor series expansion
cosVal = 0;
for i = 0:n
    cosVal = cosVal + ((-1)^i)*(x^(2*i))/factorial(2*i);
end
end
179 chars
8 lines

In this code, x is the angle in radians and n is the number of terms to compute in the series expansion. The for loop iterates from i=0 to n and adds up the contributions of each term in the series expansion to obtain the final value of cosVal.

Example usage:

main.m
>> x = pi/4;
>> n = 5;
>> cos_taylor(x, n)
ans =
    0.7071
>> cos(x)
ans =
    0.7071
87 chars
9 lines

Note that the output of our cos_taylor function matches the built-in cos function up to the number of terms specified by n.

gistlibby LogSnag