TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
bisection_method.cpp
Go to the documentation of this file.
1
16
#include <cmath>
17
#include <iostream>
18
#include <limits>
19
20
#define EPSILON \
21
1e-6
// std::numeric_limits<double>::epsilon() ///< system accuracy limit
22
#define MAX_ITERATIONS 50000
23
26
static
double
eq
(
double
i) {
27
return
(std::pow(i, 3) - (4 * i) - 9);
// original equation
28
}
29
31
template
<
typename
T>
32
int
sgn
(T val) {
33
return
(T(0) < val) - (val < T(0));
34
}
35
37
int
main
() {
38
double
a = -1, b = 1, x, z;
39
int
i;
40
41
// loop to find initial intervals a, b
42
for
(
int
i = 0; i <
MAX_ITERATIONS
; i++) {
43
z =
eq
(a);
44
x =
eq
(b);
45
if
(
sgn
(z) ==
sgn
(x)) {
// same signs, increase interval
46
b++;
47
a--;
48
}
else
{
// if opposite signs, we got our interval
49
break
;
50
}
51
}
52
53
std::cout <<
"\nFirst initial: "
<< a;
54
std::cout <<
"\nSecond initial: "
<< b;
55
56
// start iterations
57
for
(i = 0; i <
MAX_ITERATIONS
; i++) {
58
x = (a + b) / 2;
59
z =
eq
(x);
60
std::cout <<
"\n\nz: "
<< z <<
"\t["
<< a <<
" , "
<< b
61
<<
" | Bisect: "
<< x <<
"]"
;
62
63
if
(z < 0) {
64
a = x;
65
}
else
{
66
b = x;
67
}
68
69
if
(std::abs(z) < EPSILON)
// stoping criteria
70
break
;
71
}
72
73
std::cout <<
"\n\nRoot: "
<< x <<
"\t\tSteps: "
<< i << std::endl;
74
return
0;
75
}
MAX_ITERATIONS
#define MAX_ITERATIONS
Maximum number of iterations to check.
Definition
bisection_method.cpp:22
sgn
int sgn(T val)
Definition
bisection_method.cpp:32
eq
static double eq(double i)
Definition
bisection_method.cpp:26
main
int main()
Definition
bisection_method.cpp:37
numerical_methods
bisection_method.cpp
Generated by
1.12.0