Example of Using the Bisection Method in MATLAB to Calculate Real Roots of Functions

Calculate the value of the independent variable x0 such that the function f(x) satisfies f(x0)=0. First, write out the expression for the function f(x), then apply the bisection method to check the signs of the function values at the test points, continuously updating the values of the two endpoints to narrow down the interval until the solution meets the requirements.

%% Bisection method to calculate the root of the function
clear all;close all;clc;

%% Define the range and function

t=-10:0.1:15;
y=myFun1(t);
figure(1);
plot(t,y);
title('Function Curve.');

%% Set initial endpoints and error tolerance
a=-10.0;
b=10.0;
err1=1.0e-10;
max1=9999;
[x1,y1,err2]=shizhifa(@myFun1,a,b,err1,max1);
disp('x1=');
disp(x1);
disp('y=');
disp(y1);
disp('x1 error <= ');
disp(err2);
disp('End.');

%% Function definition
function  y=myFun1(x)
y=0.1*x.*x.*x-0.6*x.*x-1.5*x-1.2*sin(2*x+0.2)-3.5;
end

%% Bisection method function definition
function  [x1,y1,err2]=shizhifa(fun1,a,b,err1,max1)
%% fun1: input function
%% [a,b]: variable interval
%% err1: allowable error
%% max1: maximum iteration count
%% x1: final calculated value
%% y1: fun1(x1)

a1=a;
b1=b;

ya=feval(fun1, a1);
yb=feval(fun1, b1);

if ya*yb > 0
    disp('Warning: f(a)*f(b) > 0');
    return;
end

for k1=1:1:max1
    dx1=yb*(b1-a1)/(yb-ya);
cM=b1-dx1;
aM=cM-a1;
yM=feval(fun1, cM);

    if yM == 0
        x1=cM;
        err2=0;
        y1=0;
        break;
    elseif yb*yM > 0
        b1=cM;
        yb=yM;
    else
        a1=cM;
        ya=yM;
    end

    dx1=min(abs(dx1), aM);
    if abs(dx1) < err1
        break;
    end
    if abs(yM) < err1
        break;
    end

    cM=a1+(b1-a1)/2;
yM=feval(fun1, cM);
    if yM == 0
        x1=cM;
        err2=0;
        y1=0;
        break;
    elseif yb*yM > 0
        b1=cM;
        yb=yM;
    else
        a1=cM;
        ya=yM;
    end
    if abs(yM) < err1
        break;
    end
end

x1=cM;
y1=feval(fun1, x1);
err2=(b1-a1)/2;
end

Leave a Comment