MATLAB: How to write the summation of the maclaurin series of cos(x)

programming

How to write the summation of Maclaurin series of cos(x)?
I tried:
>> syms k x
>> SUM = symsum((-1).^(k+1) * x.^2*(k+1) / factorial(2*(k+1)), k, 0, (k+1))
% I used S = symsum(f, k, a, b) formula
I need to calculate the sum of the k+1 terms with an input of k
(k is a script which has the expression: >>k = input('enter an integer: ')
I tried it and everything is working until the last step. When all the numbers are defined, the formula didn't give me a number. Instead, I got this:
>>SUM =
x^2*symsum(((-1)^(m + 1)*(m + 1))/factorial(2*m + 2), m, 0, m + 1)
Any thoughts on how can I change my code?

Best Answer

The MacLaurin series of cos() is:
cos(x) := Sum(i = 0 to Inf) [((-1)^i / (2*i)!) * x ^ (2*i)]
[EDITED, "2*i!" replaced by "(2*i)!"]
If you want a numerical output, it is the direct approach to calculate it numerical directly:
function y = cosMacLaurin(x, k)
S = 0;
for i = 0:k
S = S + ...
end
end
I leave the "..." up to you, because I assume that this is a homework question.