-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
newton_raphson_method.cpp
68 lines (58 loc) · 1.6 KB
/
newton_raphson_method.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
60
61
62
63
64
65
66
67
68
/**
* \file
* \brief Solve the equation \f$f(x)=0\f$ using [Newton-Raphson
* method](https://en.wikipedia.org/wiki/Newton%27s_method) for both real and
* complex solutions
*
* The \f$(i+1)^\text{th}\f$ approximation is given by:
* \f[
* x_{i+1} = x_i - \frac{f(x_i)}{f'(x_i)}
* \f]
*
* \author [Krishna Vedala](https://github.com/kvedala)
* \see bisection_method.cpp, false_position.cpp
*/
#include <cmath>
#include <cstdint>
#include <ctime>
#include <iostream>
#include <limits>
constexpr double EPSILON = 1e-10; ///< system accuracy limit
constexpr int16_t MAX_ITERATIONS = INT16_MAX; ///< Maximum number of iterations
/** define \f$f(x)\f$ to find root for.
* Currently defined as:
* \f[
* f(x) = x^3 - 4x - 9
* \f]
*/
static double eq(double i) {
return (std::pow(i, 3) - (4 * i) - 9); // original equation
}
/** define the derivative function \f$f'(x)\f$
* For the current problem, it is:
* \f[
* f'(x) = 3x^2 - 4
* \f]
*/
static double eq_der(double i) {
return ((3 * std::pow(i, 2)) - 4); // derivative of equation
}
/** Main function */
int main() {
std::srand(std::time(nullptr)); // initialize randomizer
double z = NAN, c = std::rand() % 100, m = NAN, n = NAN;
int i = 0;
std::cout << "\nInitial approximation: " << c;
// start iterations
for (i = 0; i < MAX_ITERATIONS; i++) {
m = eq(c);
n = eq_der(c);
z = c - (m / n);
c = z;
if (std::abs(m) < EPSILON) { // stoping criteria
break;
}
}
std::cout << "\n\nRoot: " << z << "\t\tSteps: " << i << std::endl;
return 0;
}