-2
我有以下代碼來完成函數模板,其中輸入x在範圍[0,2 * pi]中並計算h的值e_h(x),並確定h最大限度地減少錯誤。我確實運行了這個代碼,但它沒有通過測試套件。這段代碼有什麼問題?計算錯誤的值
function [h_best,e_best]=sinDerivative(x)
% Evaluate error
% e_h(x) = abs((sin(x+h)-sin(x))/h - cos(x)) = big_O(h)
% over logarithmic scaling in values of h. The input x is assumed to be in
% radians.
% Create vector of h values and initialize variables for a loop
h=logspace(-1,-16,16); %%create a vector h=[0.1,0.01,...,1e-16]
e_best=inf; %%the error goes to zero, but the roundoff error goes to infinity
e_h=zeros(1,16);
% Loop to compute e_h values and determine hbest and ebest without max
for k=1:16
e_h(k) = abs((sin(x+h(k))-sin(x))/h(k) - cos(x));
if e_h(k) < e_best
e_best = e_h(k);
h_best = h(k);
end
end
loglogplot(e_h,h)
title(sprintf('%d-Error in Derivative of Sin Approximation %d',x,h))
xlabel('h')
ylabel('Error')
set(gca,'XDir','reverse')
saveas(gcf,'derivativeError.pdf')
end
謝謝您的回答。對於這個問題,我不得不使用'for循環'命令。 – Grace 2014-10-01 05:49:22