通过二分法求函数根

Finding a Root of a Function Through Bisection

我刚刚开始学习 MATLAB,但在寻找这个函数的根时遇到了一些问题。

其中 v0 = 36m/s,t = 4,g = 9.8m/s^2,Cd = 0.25kg/m。区间取自[100, 200],精度为10^(-4)

根据我的函数,我输入的公式是否正确。另外,这是不使用fzero求根的正确方法吗?当我 运行 它时,结果不匹配。我的教练说我应该在不到 20 次尝试的情况下接近根。谢谢

clear all; close all;

xr = 200; % right boundary
xl = 100; % left boundary

tries = 0;

for j = 1:1000
    xc = (xl + xr)/2;
    fc = sqrt((xc*9.8)/0.25)* tanh(sqrt((0.25 * 9.8) / xc) * 4) - 36;

    if fc>0
        xl = xc;
        tries = tries + 1;
    else
        xr = xc;
        tries = tries + 1;
    end

    if abs(fc)< 10^(-4)
        break
    end
end

tries % record number of attempts
xc % value of root
fc % value of function

几乎是对的。二分法要求你需要检查f(xl)f(xc)的符号。您只检查 f(xc)。因此,您只需修改两行代码:

  1. 加一行计算f(xl)
  2. 修改您的 if 语句以检查 f(xl)f(xc) 的符号。

因此,修改您的代码,我们得到:

clear all; close all;

xr = 200; % right boundary
xl = 100; % left boundary

tries = 0;

for j = 1:1000
    xc = (xl + xr)/2;
    fc = sqrt((xc*9.8)/0.25)* tanh(sqrt((0.25 * 9.8) / xc) * 4) - 36;
    %// NEW
    fl = sqrt((xl*9.8)/0.25)* tanh(sqrt((0.25 * 9.8) / xl) * 4) - 36;

    if fl*fc>0 %// CHANGE
        xl = xc;
        tries = tries + 1;
    else
        xr = xc;
        tries = tries + 1;
    end

    if abs(fc)< 10^(-4)
        break
    end
end

当我 运行 这段代码时,我的根是 xc = 144.4092 并且它在 12 (j = 12) 次迭代中收敛。我可以用符号数学工具箱验证这个根:

%// Make equation and solve for xc
syms xc;
fc = sqrt((xc*9.8)/0.25)* tanh(sqrt((0.25 * 9.8) / xc) * 4) == 36;
solve(fc)

ans =

144.40669396088800683910326198619

小数点后第二位有一些精度差异,这在您检查根输出是否小于 10-4 而不是 0 本身时是有道理的。