2014-09-30 57 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