【问题标题】:Matlab Newbie Binary Search TroubleshootMatlab 新手二分查找疑难解答
【发布时间】:2011-08-06 13:29:00
【问题描述】:

总的来说,我是 Matlab/编程的新手。我希望编写一个程序/脚本,它使用递归二进制搜索来近似 $2x - 3sin(x)+5=0$ 的根,这样一旦截断错误肯定是 $

这是我的尝试,似乎损坏了我的电脑......

%Approximating the root of f(x) = 2*x  - 3*sin(x) + 5 by binary search

%Define variables

low = input('Enter lower bound of range: ');

high = input('Enter upper bound of range: ');

mid = (low + high)/2;


%Define f_low & f_high

f_low = 2*low  - 3*sin(low) + 5;

f_high = 2*high  - 3*sin(high) + 5;

f_mid = 2*mid  - 3*sin(mid) + 5;


%Check that the entered range contains the key

while (f_low * f_high) > 0 || low > high

     disp('Invalid range')

     low = input('Enter lower bound of range: ');

     high = input('Enter upper bound of range: ');

end



%The new range

while abs(f_mid) > 0.5*10^(-5)



    if f_mid < 0

     low = mid;



    elseif f_mid > 0

      high = mid;

    end   



end



fprintf('mid = %.4f \n', mid)

我什至还没有添加迭代次数计数位(我不太确定该怎么做)并且我已经被卡住了。

感谢您的帮助。

【问题讨论】:

  • 这对于 StackOverflow 来说概率更好。为什么while循环有测试f_high * f_low &gt; 0?如果是这样的话,你显然没有把根括起来!

标签: numerical-methods matlab


【解决方案1】:

设置 high=mid 或 low=mid 后,是否会重新计算 mid 和 f_mid?如果 f_low>0 和 f_high非常平坦的函数,你可能无法获得那么小的函数值。

【讨论】:

    【解决方案2】:

    你不需要f_mid,实际上是在误导你。你只需要计算每一步的值,看看往哪个方向走。

    另外,你只是在改变低和高,但你不会再次评估 f_lowf_high。 Matlab 不是代数系统(有用于符号计算的模块,但那是另一回事),所以你没有定义 f_lowf_high 随着低和高的变化而变化:你必须在你的最后循环。

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 2013-10-22
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      相关资源
      最近更新 更多