bisection 的程式修改如下
function root=bisection(func,x_left,x_right,er)
while abs(x_left-x_right) > er % 如果 x_left 和 x_right 的距離大於誤差, 繼續切割
x_middle=(x_left+x_right)/2;
if feval(func, x_left) * feval(func, x_middle) >= 0 % 中間點和 x_left 在同一邊
x_left = x_middle;
else
x_right = x_middle;
end
end
root = (x_left+x_right)/2;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% main program
func = inline( '3*cos(x)+1' ); % 要解的函數
res = bisection(initial_guess, -5, 3, 1e-5) |