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

Solve the equation \(f(x)=0\) using false position method, also known as the Secant method. More...

#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
Include dependency graph for false_position.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 false position method, also known as the Secant 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\cdot f(b_i) - b_i\cdot f(a_i)}{f(b_i) - f(a_i)} \]

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, bisection_method.cpp

Function Documentation

◆ eq()

static double eq ( double  i)
static

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

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

◆ main()

int main ( void  )

main function

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

◆ sgn()

template<typename T >
int sgn ( val)

get the sign of any given number

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