Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
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:

Macros

#define EPSILON   1e-6
 
#define MAX_ITERATIONS   50000
 Maximum number of iterations to check.
 

Functions

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

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

26  {
27  return (std::pow(i, 3) - (4 * i) - 9); // original equation
28 }
Here is the call graph for this function:

◆ eq_der()

static double eq_der ( double  i)
static

define the derivative function \(f'(x)\)

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

◆ main()

int main ( )

Main function

37  {
38  std::srand(std::time(nullptr)); // initialize randomizer
39 
40  double z, c = std::rand() % 100, m, n;
41  int i;
42 
43  std::cout << "\nInitial approximation: " << c;
44 
45  // start iterations
46  for (i = 0; i < MAX_ITERATIONS; i++) {
47  m = eq(c);
48  n = eq_der(c);
49 
50  z = c - (m / n);
51  c = z;
52 
53  if (std::abs(m) < EPSILON) // stoping criteria
54  break;
55  }
56 
57  std::cout << "\n\nRoot: " << z << "\t\tSteps: " << i << std::endl;
58  return 0;
59 }
Here is the call graph for this function:
std::srand
T srand(T... args)
MAX_ITERATIONS
#define MAX_ITERATIONS
Maximum number of iterations to check.
Definition: newton_raphson_method.cpp:22
eq
static double eq(double i)
Definition: newton_raphson_method.cpp:26
eq_der
static double eq_der(double i)
Definition: newton_raphson_method.cpp:32
std::cout
std::rand
T rand(T... args)
std::endl
T endl(T... args)
std::time
T time(T... args)
std::pow
T pow(T... args)