-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This commit adds a new file for implementing bisection method.
- Loading branch information
1 parent
6376bf4
commit 3067ba4
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |