1

I am just learning MATLAB and I am having some issues with finding the roots of this function.

The Function

Where v0 = 36m/s, t = 4, g = 9.8m/s^2, and Cd = 0.25kg/m. The interval is from [100, 200] with a precision of 10^(-4)

Based on my function, did I input my equation correctly. In addition, is this the correct way to find the roots without using fzero? When I run it, the results don't match up. My instructor said I should be close to a root in less than 20 attempts. Thanks.

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
4

1 回答 1

2

几乎说对了。二分法要求您需要检查 的符号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

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

于 2015-01-13T04:44:47.957 回答