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

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

## main()

int main | ( | void |  | ) |

main function

{
double a = -1, b = 1, x, z;
int i;
// loop to find initial intervals a, b
for (int i = 0; i < MAX_ITERATIONS; i++) {
z = eq(a);
x = eq(b);
if (sgn(z) == sgn(x)) { // same signs, increase interval
b++;
a--;
} else { // if opposite signs, we got our interval
break;
}
}
std::cout << "\nFirst initial: " << a;
std::cout << "\nSecond initial: " << b;
// start iterations
for (i = 0; i < MAX_ITERATIONS; i++) {
x = (a + b) / 2;
z = eq(x);
std::cout << "\n\nz: " << z << "\t[" << a << " , " << b
<< " | Bisect: " << x << "]";
if (z < 0) {
a = x;
} else {
b = x;
}
if (std::abs(z) < EPSILON) // stoping criteria
break;
}
std::cout << "\n\nRoot: " << x << "\t\tSteps: " << i << std::endl;
return 0;
}
std::cout
MAX_ITERATIONS
#define MAX_ITERATIONS
Maximum number of iterations to check.
Definition: bisection_method.cpp:22
sgn
int sgn(T val)
Definition: bisection_method.cpp:32
eq
static double eq(double i)
Definition: bisection_method.cpp:26
std::endl
T endl(T... args)
EPSILON
constexpr double EPSILON
system accuracy limit
Definition: newton_raphson_method.cpp:20
Here is the call graph for this function:

## sgn()

template<typename T >

int sgn | ( | T | val | ) |

get the sign of any given number

{
return (T(0) < val) - (val < T(0));
}