Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
bisection_method.cpp File Reference

Solve the equation \(f(x)=0\) using bisection method More...

#include <cmath>
#include <iostream>
#include <limits>
Include dependency graph for bisection_method.cpp:

Macros

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

Functions

static double eq (double i)
 
template<typename T >
int sgn (T val)
 
int main ()
 

Detailed Description

Solve the equation \(f(x)=0\) using bisection method

Given two points \(a\) and \(b\) such that \(f(a)<0\) and \(f(b)>0\), then the \((i+1)^\text{th}\) approximation is given by:

\[ x_{i+1} = \frac{a_i+b_i}{2} \]

For the next iteration, the interval is selected as: \([a,x]\) if \(x>0\) or \([x,b]\) if \(x<0\). The Process is continued till a close enough approximation is achieved.

See also
newton_raphson_method.cpp, false_position.cpp, secant_method.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:

◆ main()

int main ( void  )

main function

37  {
38  double a = -1, b = 1, x, z;
39  int i;
40 
41  // loop to find initial intervals a, b
42  for (int i = 0; i < MAX_ITERATIONS; i++) {
43  z = eq(a);
44  x = eq(b);
45  if (sgn(z) == sgn(x)) { // same signs, increase interval
46  b++;
47  a--;
48  } else { // if opposite signs, we got our interval
49  break;
50  }
51  }
52 
53  std::cout << "\nFirst initial: " << a;
54  std::cout << "\nSecond initial: " << b;
55 
56  // start iterations
57  for (i = 0; i < MAX_ITERATIONS; i++) {
58  x = (a + b) / 2;
59  z = eq(x);
60  std::cout << "\n\nz: " << z << "\t[" << a << " , " << b
61  << " | Bisect: " << x << "]";
62 
63  if (z < 0) {
64  a = x;
65  } else {
66  b = x;
67  }
68 
69  if (std::abs(z) < EPSILON) // stoping criteria
70  break;
71  }
72 
73  std::cout << "\n\nRoot: " << x << "\t\tSteps: " << i << std::endl;
74  return 0;
75 }
Here is the call graph for this function:

◆ sgn()

template<typename T >
int sgn ( val)

get the sign of any given number

32  {
33  return (T(0) < val) - (val < T(0));
34 }
sgn
int sgn(T val)
Definition: bisection_method.cpp:32
EPSILON
constexpr double EPSILON
system accuracy limit
Definition: newton_raphson_method.cpp:20
std::cout
std::endl
T endl(T... args)
MAX_ITERATIONS
#define MAX_ITERATIONS
Maximum number of iterations to check.
Definition: bisection_method.cpp:22
eq
static double eq(double i)
Definition: bisection_method.cpp:26
std::pow
T pow(T... args)