Skip to content

Commit

Permalink
[ADD] bisection_method.cpp
Browse files Browse the repository at this point in the history
This commit adds a new file for implementing bisection method.
  • Loading branch information
kushchoudhary98 authored Oct 6, 2023
1 parent 6376bf4 commit 3067ba4
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions math/bisection_method.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <iostream>
#include <math.h>
using namespace std;

double f(double x) {//can add your own function
return cos(x) - x*exp(x);
}

void bisection(double x, double y, double error = 0.00001) {
static bool flag = false;//to make sure the 'invalid interval' message is printed correctly
if(f(x)*f(y) >= 0) {
if(flag == false) cout << "The interval [a,b] provided is not valid" << endl;
return;
}

flag = true;
double z = (x+y)/2;
if(abs(x-y) <= error) {
cout << "The approximate root is : " << z << endl;
return;
}

if(f(z) == 0.0) {
cout << "The root is : " << z << endl;
return;
}
else {
if(f(x)*f(z) < 0) bisection(x, z, error);
else if(f(z)*f(y) < 0) bisection(y, z, error);
else {
cout << "The given function does not follow the required assumtions" << endl;
return;
}
}
}

int main(void) {
double a, b;
cout << "Enter the two guesses : " << endl;
cin >> a;
cin >> b;
bisection(a, b);
}

0 comments on commit 3067ba4

Please sign in to comment.