TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
newton_raphson_method.cpp
Go to the documentation of this file.
1
15
#include <cmath>
16
#include <cstdint>
17
#include <ctime>
18
#include <iostream>
19
#include <limits>
20
21
constexpr
double
EPSILON
= 1e-10;
22
constexpr
int16_t
MAX_ITERATIONS
= INT16_MAX;
23
30
static
double
eq
(
double
i) {
31
return
(std::pow(i, 3) - (4 * i) - 9);
// original equation
32
}
33
40
static
double
eq_der
(
double
i) {
41
return
((3 * std::pow(i, 2)) - 4);
// derivative of equation
42
}
43
45
int
main
() {
46
std::srand(std::time(
nullptr
));
// initialize randomizer
47
48
double
z = NAN, c = std::rand() % 100, m = NAN, n = NAN;
49
int
i = 0;
50
51
std::cout <<
"\nInitial approximation: "
<< c;
52
53
// start iterations
54
for
(i = 0; i <
MAX_ITERATIONS
; i++) {
55
m =
eq
(c);
56
n =
eq_der
(c);
57
58
z = c - (m / n);
59
c = z;
60
61
if
(std::abs(m) <
EPSILON
) {
// stoping criteria
62
break
;
63
}
64
}
65
66
std::cout <<
"\n\nRoot: "
<< z <<
"\t\tSteps: "
<< i << std::endl;
67
return
0;
68
}
eq
static double eq(double i)
Definition
newton_raphson_method.cpp:30
eq_der
static double eq_der(double i)
Definition
newton_raphson_method.cpp:40
MAX_ITERATIONS
constexpr int16_t MAX_ITERATIONS
Maximum number of iterations.
Definition
newton_raphson_method.cpp:22
EPSILON
constexpr double EPSILON
system accuracy limit
Definition
newton_raphson_method.cpp:21
main
int main()
Definition
newton_raphson_method.cpp:45
numerical_methods
newton_raphson_method.cpp
Generated by
1.12.0