TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
newton_raphson_method.cpp File Reference

Solve the equation \(f(x)=0\) using Newton-Raphson method for both real and complex solutions. More...

#include <cmath>
#include <cstdint>
#include <ctime>
#include <iostream>
#include <limits>
Include dependency graph for newton_raphson_method.cpp:

Go to the source code of this file.

Functions

static double eq (double i)
 
static double eq_der (double i)
 
int main ()
 

Variables

constexpr double EPSILON = 1e-10
 system accuracy limit
 
constexpr int16_t MAX_ITERATIONS = INT16_MAX
 Maximum number of iterations.
 

Detailed Description

Solve the equation \(f(x)=0\) using Newton-Raphson method for both real and complex solutions.

The \((i+1)^\text{th}\) approximation is given by:

\[ x_{i+1} = x_i - \frac{f(x_i)}{f'(x_i)} \]

Author
Krishna Vedala
See also
bisection_method.cpp, false_position.cpp

Definition in file newton_raphson_method.cpp.

Function Documentation

◆ eq()

static double eq ( double i)
static

define \(f(x)\) to find root for. Currently defined as:

\[ f(x) = x^3 - 4x - 9 \]

Definition at line 30 of file newton_raphson_method.cpp.

30 {
31 return (std::pow(i, 3) - (4 * i) - 9); // original equation
32}

◆ eq_der()

static double eq_der ( double i)
static

define the derivative function \(f'(x)\) For the current problem, it is:

\[ f'(x) = 3x^2 - 4 \]

Definition at line 40 of file newton_raphson_method.cpp.

40 {
41 return ((3 * std::pow(i, 2)) - 4); // derivative of equation
42}

◆ main()

int main ( void )

Main function

Definition at line 45 of file newton_raphson_method.cpp.

45 {
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

Variable Documentation

◆ EPSILON

double EPSILON = 1e-10
constexpr

system accuracy limit

Definition at line 21 of file newton_raphson_method.cpp.

◆ MAX_ITERATIONS

int16_t MAX_ITERATIONS = INT16_MAX
constexpr

Maximum number of iterations.

Definition at line 22 of file newton_raphson_method.cpp.