-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBisection.cpp
59 lines (45 loc) · 1003 Bytes
/
Bisection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<bits/stdc++.h>
using namespace std;
double func(double x)
{
return 4*exp(-x)*sin(x)-1;
}
void Bisection(double a, double b, double error)
{
if (func(a) * func(b) >= 0)
{
cout << "There is no root between a and b.";
return;
}
double x = a;
int iteration = 1;
while(abs(b-a)>error)
{
cout << fixed
<< " Iteration=" << iteration
<< "\ta=" << a
<< "\tb=" << b;
x = (a+b)/2;
if(func(x) == 0.0)
break;
else if (func(x)*func(a) < 0)
{
b = x;
}
else
{
a = x;
}
cout << "\tx" << iteration << "=" << x
<< setprecision(5) << "\tErr" << "=" << abs(b-a)
<< endl << endl;
iteration++;
}
cout << endl << endl << " The root is " << setprecision(3) << x << endl;
}
int main()
{
double a = 0, b = 0.5, error = 0.0001;
Bisection(a, b, error);
return 0;
}