Taylor Series Approximation for Cosine

2 views (last 30 days)
David Meixell
David Meixell on 4 Oct 2020
Commented: John D'Errico on 4 Oct 2020
For the following code to solve the taylor series approximation for cosine, I'm not getting the expected value for pi/2. Nor is the convergence flag ever getting to the desired value, which seems odd. I can successfully get values (expected) for pi/4 and pi- but pi/2 is all over the place. Is anyone able to see where I went wrong?
function [approxValue, diff, convFlag] = taylorEst(x, actualCos)
% Finds the approximate value of cos(x). Solves until error is less than
% 1e-4. The series for cosine is only has even powers, thus the 'n'
% variable advancing by 2 each iteration. Returns the series
% approximation and error between 'true' and 'estimated' values of
% cosine.
approxValue = 1; %initial value for series approximation
n = 2; %Starts at 2 due to even power for cosine series
k = 1; %number of terms
diff = 1; %initial difference value
relError = 1e-8; % Required relative error
myrel = 1; %initial value for error
%Solve the series approximation until difference between Matlab's
%internal cos(x) and calculated cos(x) is less than 1e-4 or 20 iterations occur.
while diff > .0001 && (k < 20)
k = k + 1;
oldVal = approxValue;
approxValue = approxValue + ((-1) .^ (k-1) .* x .^ n) ./ factorial(n);
diff = abs(actualCos - approxValue); %Compare true to approx value
n = n + 2; %Only applies positive powers for cosine series
myrel = abs(((approxValue - oldVal) / approxValue));
end
disp(myrel)
disp(relError)
%Determine if the process has converged
if myrel <= relError
convFlag = 1;
else
convFlag = 0;
end
end
  3 Comments
David Meixell
David Meixell on 4 Oct 2020
Regarding the convergence flag, oldVal never equals zero, right? It's immediately initialized as 'oldVal = approxValue' and approxValue = 1, so myrel is never 1 and dividing by zero should never be encountered- unless I'm totally missing something.
John D'Errico
John D'Errico on 4 Oct 2020
Really? So approxvalue NEVER changes? It is ALWAYS 1? I am so surprised. What then is the purpose of thise line?
approxValue = approxValue + ((-1) .^ (k-1) .* x .^ n) ./ factorial(n);
Admittedly, it will be exceedingly rare for that value to ever be zero, only for example at x=pi/2 would that be possible.

Sign in to comment.

Answers (0)

Categories

Find more on Mathematics and Optimization in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!