Algorithms_in_C++ 1.0.0
Set of 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:

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

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 \]

30 {
31 return (std::pow(i, 3) - (4 * i) - 9); // original equation
32}
T pow(T... args)
Here is the call graph for this function:

◆ 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 \]

40 {
41 return ((3 * std::pow(i, 2)) - 4); // derivative of equation
42}
Here is the call graph for this function:

◆ main()

int main ( void )

Main function

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}
T endl(T... args)
static double eq(double i)
Definition newton_raphson_method.cpp:30
static double eq_der(double i)
Definition newton_raphson_method.cpp:40
constexpr int16_t MAX_ITERATIONS
Maximum number of iterations.
Definition newton_raphson_method.cpp:22
constexpr double EPSILON
system accuracy limit
Definition newton_raphson_method.cpp:21
T rand(T... args)
T srand(T... args)
T time(T... args)
Here is the call graph for this function: