[Bairstow]
% MATLAB Code for Bairstow's Method
clear all;
% Define the coefficients of the polynomial f(x)
% Coefficients of f(x) Order: constant to high n
coeff = [1.25, -3.875, 2.125, 2.75, -3.5, 1];
% Initial guesses for r and s
r = -1;
s = -1;
% Error tolerance
epsilon_s = 0.01; % 1%
% Maximum iterations to prevent infinite loops
max_iter = 100;
% Number of iterations counter
iter = 0;
while true
iter = iter + 1;
% Synthetic division to calculate b and c arrays
n = length(coeff) - 1; % Degree of the polynomial
b = zeros(size(coeff));
c = zeros(size(coeff));
% Compute b array using synthetic division
b(n+1) = coeff(n+1);
b(n) = coeff(n) + r * b(n+1);
for i = n-1:-1:1
b(i) = coeff(i) + r * b(i+1) + s * b(i+2);
end
fprintf('b values are: [');
fprintf('%f ', b);
fprintf(']\n');
% Compute c array using synthetic division on b array
c(n+1) = b(n+1);
c(n) = b(n) + r * c(n+1);
for i = n-1:-1:2
c(i) = b(i) + r * c(i+1) + s * c(i+2);
end
fprintf('c values are: [');
fprintf('%f ', c);
fprintf(']\n');
% Update r and s using Newton-Raphson method
det = c(3)*c(3) - c(2)*c(4); % Determinant of Jacobian matrix
if abs(det) < eps % Prevent division by zero
error('Determinant too small, method failed.');
end
dr = (-b(2)*c(3) + b(1)*c(4)) / det;
ds = (-b(1)*c(3) + b(2)*c(2)) / det;
r_new = r + dr;
s_new = s + ds;
% Check for convergence
err_r = abs(dr / r_new) * 100; % Relative error in r
err_s = abs(ds / s_new) * 100; % Relative error in s
if err_r < epsilon_s && err_s < epsilon_s
break;
end
if iter >= max_iter
error('Maximum iterations reached without convergence.');
end
% Update r and s for next iteration
r = r_new;
s = s_new;
end
% Display results for quadratic factor found (x^2 + rx + s)
fprintf('Converged after %d iterations.\n', iter);
fprintf('Quadratic factor: x^2 + (%.4f)x + (%.4f)\n', r, s);
% Use quadratic formula to find roots of x^2 + rx + s
root_1 = (r + sqrt(r^2 + 4*s)) / 2;
root_2 = (r - sqrt(r^2 + 4*s)) / 2;
fprintf('1st Root of quadratic factor: %.4f + %.4f i\n', real(root_1), imag(root_1));
fprintf('2nd Root of quadratic factor: %.4f + %.4f i\n', real(root_2), imag(root_2));
% Deflate the polynomial by dividing by (x^2 + rx + s)
remaining_poly_coeffs = b(3:end);
fprintf('Remaining polynomial coefficients after deflation:\n');
disp(remaining_poly_coeffs);