Taylor Series Approximation for Cosine
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
John D'Errico
2020-10-4
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.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Mathematics and Optimization 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!