C++ program to implement bisection method

In this tutorial, we are going to learn about the implementation of the bisection method in C++. This method is used to find roots in a continuous function between two given interval, given the two values to be in the opposite signs. The method involves repeatedly bisecting of the interval and ultimately reaching to the desired root. It is a very simple and robust method, but relatively slow.

This method is also called interval halving method, binary search method, or dichotomy method.

Explanation: Bisection Method in C++

Let f(x) be a function in an interval [a,b] , where f  is continuous and f(a) and f(b) have opposite signs. By intermediate value theorem, there must exist one root that lies between (a,b).

  • At each step divide the interval into halves c=a+b/2 and find the value of f(c).
  • Either f(c)=0 then we can stop directly as c will be itself the root.
  • Otherwise, f(a) and f(c) have opposite signs or f(b) and f(c) have opposite signs.
  • For the first case set a=c ,else set b=c.
  • Continue the steps again until you reached your result.
  • After some iterations the value of f(a) and f(b) will converge there you can say it is the root for the polynomial.

Implementation of CPP code: C++ Program to perform bisection method

We can find the root of a given polynomial in C++ using this bisection method.

#include<iostream>
 
using namespace std;
 
//function used is x^3-2x^2+3
double func(double x)
{
    return x*x*x - 2*x*x + 3;
}
 

double c;
 
void bisection(double a,double b)
{
    if(func(a) * func(b) >= 0)
    {
        cout<<"Incorrect a and b";
        return;
    }
 
    c=a;
 
    while ((b-a) >= 0.01) //tell about interval is sufficently small
    {
        c = (a+b)/2;
        if (func(c) == 0.0){
            
            break;
        }
        else if (func(c)*func(a) < 0){
               
                b=c;
        }
        else{
                
                a=c;
        }
    }
}
 
int main()
{
    double a,b;
    a=-10;
    b=20;
    bisection(a,b); 
    cout<<"\n";
    cout<<"The value of root is = "<<c<<endl;
 
    return 0;
}
Output:
The value of root is = -0.998535

For any query regarding this post please comment down below, we will try to resolve it soon. Thanks 🙂

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *