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

29 {
30 return (std::pow(i, 3) - (4 * i) - 9); // original equation
31}
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 \]

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

◆ main()

int main ( void )

Main function

44 {
45 std::srand(std::time(nullptr)); // initialize randomizer
46
47 double z = NAN, c = std::rand() % 100, m = NAN, n = NAN;
48 int i = 0;
49
50 std::cout << "\nInitial approximation: " << c;
51
52 // start iterations
53 for (i = 0; i < MAX_ITERATIONS; i++) {
54 m = eq(c);
55 n = eq_der(c);
56
57 z = c - (m / n);
58 c = z;
59
60 if (std::abs(m) < EPSILON) { // stoping criteria
61 break;
62 }
63 }
64
65 std::cout << "\n\nRoot: " << z << "\t\tSteps: " << i << std::endl;
66 return 0;
67}
T endl(T... args)
static double eq(double i)
Definition newton_raphson_method.cpp:29
static double eq_der(double i)
Definition newton_raphson_method.cpp:39
constexpr int16_t MAX_ITERATIONS
Maximum number of iterations.
Definition newton_raphson_method.cpp:21
constexpr double EPSILON
system accuracy limit
Definition newton_raphson_method.cpp:20
T rand(T... args)
T srand(T... args)
T time(T... args)
Here is the call graph for this function: