# Bisection Method Solution in C++ Programming

## Bisection Method Definition

The bisection method separates the interval and subdivides the interval in which the root of the equation lies. The principle behind this method is the intermediate theorem for continuous functions. It works by narrowing the gap between the positive and negative intervals until it closes in on the correct answer. This method narrows the gap by taking the average of the positive and negative intervals. It is a simple method, and it is relatively slow. The bisection method is also known as interval halving method, root-finding method, binary search method or dichotomy method.

Let, consider a continuous function âfâ which is defined on the closed interval [a, b], is given with f(a) and f(b) of different signs. Then by intermediate theorem, there exists a point x belong to (a, b) for which f(x) =0.

## Bisection Method Algorithm

Bisection Method Algorithms presents in the following way

For any continuous function f(x),

• Find two points, say a and b such that a < b and f(a)* f(b) < 0
• Find the midpoint of a and b, say âtâ
• t is the root of the given function if f(t) = 0; else follow the next step
• Divide the interval [a, b]
• If f(t)*f(b) <0, let a = t
• Else if f(t) *f(a), let b = t
• Repeat above three steps until f(t) = 0.

The bisection method is an approximation method to find the roots of the given equation by repeatedly dividing the interval. This method will divide the interval until the resulting interval is found, which is extremely small.

## Bisection Method in c / c++ programming

``````#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;

#define f(x) 3*x*x-6*x+2

int main()
{
float x1,x2,x0,f1,f2,f0,e=1;
cout<< "enter the initial guess x1 and x2:";
cin>>x1>>x2;
do
{
f1=f(x1);
f2=f(x2);
if(f1*f2>0)
{
cout<< "the root does not bracket the root";
exit(0);
}
else
{
x0=(x1+x2)/2;   //working formula
f0=f(x0);
e=fabs((x2-x1)/x2);
if(f1*f0<0)
{
x2=x0;
}
else
{
x1=x0;
}
}
}while(e>=0.0001&&f0!=0);
cout<<"nthe root of the equation ="<<x0;
return 0;
}``````

Output of the program :

Enter the initial guess x1 and x2 : 1
2
The root of the equation = 1.57739

You may like some other numerical method Questions :