File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments