通过二分法找到函数的根

时间:2015-01-13 04:06:32

标签: matlab math equation bisection

我只是在学习MATLAB,而且我在找到这个函数的根源时遇到了一些问题。

The Function

其中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

1 个答案:

答案 0 :(得分:2)

几乎让它正确无误。二分法要求您检查f(xl)f(xc)的符号。您只需检查f(xc)。因此,您只需要用两行修改代码:

  1. 添加一行以计算f(xl)
  2. 修改您的if语句,以检查f(xl)f(xc)
  3. 的签名

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

    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
    

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

相关问题