Given equation: f(x) = x3-x-1
Code for bisection method :
#include <iostream>
#include <cmath>
using namespace std;
// Define the function f(x) = x^3 - x - 1
double f(double x) {
return x*x*x - x - 1;
}
// Bisection Method to find root
void bisection(double a, double b, double tolerance) {
if (f(a) * f(b) >= 0) {
cout << "You have not assumed right a and b." << endl;
return;
}
double c = a;
while ((b - a) >= tolerance) {
// Find middle point
c = (a + b) / 2;
// Check if middle point is root
if (f(c) == 0.0) {
break;
}
// Decide the side to repeat the steps
else if (f(c) * f(a) < 0) {
b = c;
}
else {
a = c;
}
}
cout << "The value of root is : " << c << endl;
}
int main() {
double a = 1, b = 2; // Initial guess values
double tolerance = 0.00001; // Tolerance for accuracy
bisection(a, b, tolerance);
return 0;
}
Output for the code