MATLAB - 正割法产生 NaN

MATLAB - Secant method produces NaN

我正在 MATLAB 中编写一个割线方法,我想精确地迭代 n 次。

function y = secantmeth(f,xn_2,xn_1,n)

xn = (xn_2*f(xn_1) - xn_1*f(xn_2))/(f(xn_1) - f(xn_2));
k = 0;
while (k < n)
    k = k + 1;
    xn_2 = xn_1;
    xn_1 = xn;
    xn = (xn_2*f(xn_1) - xn_1*f(xn_2))/(f(xn_1) - f(xn_2));
end
y = xn;
end

我相信该方法适用于较小的 n 值,但即使像 n = 9 这样的值也会产生 NaN。我的猜测是数量 f(xn_1) - f(xn_2) 大约为零,这会导致此错误。我怎样才能避免这种情况?

示例:

Input 1

eqn = @(x)(x^2 + x -9)

secantmeth(eqn,2,3,5)

Input 2

eqn = @(x)(x^2 + x - 9)

secantmeth(eqn, 2, 3, 9)

Output 1

2.7321

Output 2

NaN

xn_2xn_1 完全相等时,xn 的值将是 NaN,这会导致 0/0 条件。您需要在 while 循环条件中进行额外检查,以查看 xn_1x_n 是否相等(或者,更好的是 within some small tolerance of one another),从而表明循环已经收敛于解决方案,无法进一步迭代:

...
while (k < n) && (xn_1 ~= xn)
  k = k + 1;
  xn_2 = xn_1;
  xn_1 = xn;
  xn = (xn_2*f(xn_1) - xn_1*f(xn_2))/(f(xn_1) - f(xn_2));
end
...

一样,如果您想尝试获得更准确的近似值,则可以在 while 循环后继续使用不同的方法:

...
if (xn_1 == xn)  % Previous loop couldn't iterate any further
  % Try some new method
end
...

再次,我建议通读 this question 以了解浮点比较的一些陷阱(即 ==~= 通常不是最好的运算符用于浮点数)。