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!