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
21constexpr double EPSILON = 1e-10;
22constexpr int16_t MAX_ITERATIONS = INT16_MAX;
23
30static double eq(double i) {
31 return (std::pow(i, 3) - (4 * i) - 9); // original equation
32}
33
40static double eq_der(double i) {
41 return ((3 * std::pow(i, 2)) - 4); // derivative of equation
42}
43
45int 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}
static double eq(double i)
static double eq_der(double i)
constexpr int16_t MAX_ITERATIONS
Maximum number of iterations.
constexpr double EPSILON
system accuracy limit