计算错误的值

时间:2014-09-30 23:56:46

标签: matlab

我有以下代码来完成函数模板,该函数模板在[0,2 * pi]范围内输入x并计算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 个答案:

答案 0 :(得分: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