Skip to content

Commit 3067ba4

Browse files
[ADD] bisection_method.cpp
This commit adds a new file for implementing bisection method.
1 parent 6376bf4 commit 3067ba4

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

math/bisection_method.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <iostream>
2+
#include <math.h>
3+
using namespace std;
4+
5+
double f(double x) {//can add your own function
6+
return cos(x) - x*exp(x);
7+
}
8+
9+
void bisection(double x, double y, double error = 0.00001) {
10+
static bool flag = false;//to make sure the 'invalid interval' message is printed correctly
11+
if(f(x)*f(y) >= 0) {
12+
if(flag == false) cout << "The interval [a,b] provided is not valid" << endl;
13+
return;
14+
}
15+
16+
flag = true;
17+
double z = (x+y)/2;
18+
if(abs(x-y) <= error) {
19+
cout << "The approximate root is : " << z << endl;
20+
return;
21+
}
22+
23+
if(f(z) == 0.0) {
24+
cout << "The root is : " << z << endl;
25+
return;
26+
}
27+
else {
28+
if(f(x)*f(z) < 0) bisection(x, z, error);
29+
else if(f(z)*f(y) < 0) bisection(y, z, error);
30+
else {
31+
cout << "The given function does not follow the required assumtions" << endl;
32+
return;
33+
}
34+
}
35+
}
36+
37+
int main(void) {
38+
double a, b;
39+
cout << "Enter the two guesses : " << endl;
40+
cin >> a;
41+
cin >> b;
42+
bisection(a, b);
43+
}

0 commit comments

Comments
 (0)