%% Copyright (c) 2025 Duong Ngoc Son <son@duongnotes.com>

%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
%% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
%% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
%% HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
%% SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
%% LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%% THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
%% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

%' @title Bisection Method
%'
%' @description
%' Find an approximate root of an equation using Bisection Method.
%'
%' @example
%' f(x) = x^4 - 3 * x + 1, [a, b] = [1, 2], root = 1,307486 ... 

function [root, iter] = Bisection(f, a, b, tol, maxiter)
	iter = 0;
	fa = f(a);
	fb = f(b);
	while (abs(b - a) > tol & iter < maxiter)
		c = (a + b) / 2;
		fc = f(c);
		if (sign(fc) * sign(fa) < 0)
			b = c;
			fb = fc;
			iter = iter + 1;
		elseif (sign(fc) * sign(fb) < 0)
			a = c;
			fa = fc;
			iter = iter + 1;
		else
			b = c;
			a = c;
			iter = iter + 1;
		end
	end
	root = (a + b) / 2;
end

% Ví dụ áp dụng: Hàm f(x) = x^4 - 3 * x + 1. Tìm nghiệm của phương
% trình f(x) = 0 trong khoảng tách nghiệm [1, 2] với sai số tol < 1e-6.

clc;
f = @(x) x^4 - 3 * x + 1;
[root, iterations] = Bisection(f, 1, 2, 1e-6, 1000);
fprintf('Nghiệm x = %d tìm thấy sau %d bước lặp.\n', root, iterations);


