一般来说,我是 Matlab/编程的新手。我希望编写一个程序/脚本,它使用递归二进制搜索来近似 $2x - 3sin(x)+5=0$ 的根,这样一旦截断错误肯定是 $< 0.5 \times 10 ^{ -5}$ 并打印出迭代次数以及根的估计值。
这是我的尝试,似乎破坏了我的计算机...
%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)
我什至没有添加迭代次数计数位(我不太确定该怎么做)并且我已经被卡住了。
谢谢你的帮助。