TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
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:

Go to the source code of this file.

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

Definition in file bisection_method.cpp.

Macro Definition Documentation

◆ EPSILON

#define EPSILON    1e-6

Definition at line 20 of file bisection_method.cpp.

20#define EPSILON \
21 1e-6 // std::numeric_limits<double>::epsilon() ///< system accuracy limit

◆ MAX_ITERATIONS

#define MAX_ITERATIONS   50000

Maximum number of iterations to check.

Definition at line 22 of file bisection_method.cpp.

Function Documentation

◆ eq()

static double eq ( double i)
static

define \(f(x)\) to find root for

Definition at line 26 of file bisection_method.cpp.

26 {
27 return (std::pow(i, 3) - (4 * i) - 9); // original equation
28}

◆ main()

int main ( void )

main function

Definition at line 37 of file bisection_method.cpp.

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}
#define MAX_ITERATIONS
Maximum number of iterations to check.
int sgn(T val)
static double eq(double i)

◆ sgn()

template<typename T >
int sgn ( T val)

get the sign of any given number

Definition at line 32 of file bisection_method.cpp.

32 {
33 return (T(0) < val) - (val < T(0));
34}