2014-09-30 62 views
-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 

回答

1

我不確定你是否在試圖以正確的方式去做任何事情,但是在這裏。

  • 由於您使用的所有函數都是向量化的,因此不需要循環(假設x是標量輸入)。我已經替換了循環。
  • Matlab有很多超越蠻力猜測和檢查的優化工具。我已經添加了一個使用fsolve的例子,它比蠻力方法找到更好的值。
  • 繪圖功能是loglog,而不是loglogplot

這裏就是你要找的工作代碼:

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] 

    % Compute the error vector 
    e_h = abs((sin(x+h)-sin(x))./h - cos(x)); 

    % Find the best h and error from list 
    [e_best, i_best] = min(e_h); 
    h_best = h(i_best); 

    % Find optimal h and error 
    Efun = @(in) abs((sin(x+in)-sin(x))./in - cos(x)); 
    h_guess = 1e-7; 
    [h_opt, e_opt] = fsolve(Efun, h_guess, ... 
    optimoptions('fsolve','TolFun', 1e-12)); 

    % Display results 
    fprintf('Best values for h: %g e: %g\n', h_best, e_best); 
    fprintf('Optimized values for h: %g e: %g\n', h_opt, e_opt); 

    % Plot results 
    loglog(h,e_h); 
    hold on; 
    loglog(h_opt,e_opt, 'go'); 
    hold off; 
    title('Error in Derivative of Sin Approximation'); 
    xlabel('h (units?)'); 
    ylabel('Error (units?)'); 
    set(gca,'XDir','reverse'); 
end 
+0

謝謝您的回答。對於這個問題,我不得不使用'for循環'命令。 – Grace 2014-10-01 05:49:22