0% found this document useful (0 votes)
4 views2 pages

Bisection Method C++

The document contains a C++ program that implements the Bisection Method to find the root of the equation x^3 - 4x - 9 = 0. It prompts the user for initial guesses and desired accuracy, checks if the guesses are valid, and iteratively narrows down the interval until the root is found within the specified accuracy. The program outputs the iterations and the final root value.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Bisection Method C++

The document contains a C++ program that implements the Bisection Method to find the root of the equation x^3 - 4x - 9 = 0. It prompts the user for initial guesses and desired accuracy, checks if the guesses are valid, and iteratively narrows down the interval until the root is found within the specified accuracy. The program outputs the iterations and the final root value.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

//Bisection Method

//Find the root of the equation x^3 - 4x - 9 = 0 using Bisection Method


#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

double f(double x); //function declaration


double f(double x) //function defining
{
double E = pow(x, 3.0) - 4*x - 9; //equation
return E;
}

int main()
{
int iter = 0;
double a, b, c, e, fa, fb, fc;
cout.precision(4);
cout.setf(ios::fixed);

a: cout << "Enter the initial guesses,\na = ";


cin >> a;
cout << "\nb = ";
cin >> b;
cout << "\nEnter the desired accuracy:" << endl;
cin >> e; //e stands for accuracy, 0.0001 means correct upto 3 decimal points

if (f(a) * f(b) > 0)


{
cout << "Please enter a differnt guesses" << endl;
goto a;
}
else
{
cout << "iter" << setw(14) << "a" << setw(18) << "b" << setw(18) << "c" <<
setw(18) << "|a-b|" << endl;
cout << "------------------------------------------------------------------
-------------"<< endl;
}

//calculation
while(fabs(a-b)>=e)
{
fa = f(a);
fb = f(b);
c = (a + b) / 2.0;
fc = f(c);
iter++;

cout << iter << setw(14) << a << setw(18) << b << setw(18) << c << setw(18)
<< fabs(a - b) << endl;

if (fc == 0)
{
cout << "The root of the equation is " << c << endl;
return 0;
}
else if (fa * fc > 0)
{
a = c;
}
else if (fa * fc < 0)
{
b = c;
}
}
cout << "The root of the equation is " << c << endl;
return 0;
}

You might also like