TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
false_position.cpp
Go to the documentation of this file.
1
25
#include <cmath>
26
#include <iostream>
27
32
namespace
numerical_methods
{
38
namespace
false_position
{
44
static
float
eq
(
float
x) {
45
return
(x * x - x);
// original equation
46
}
47
55
static
float
regula_falsi
(
float
x1,
float
x2,
float
y1,
float
y2) {
56
float
diff = x1 - x2;
57
if
(diff < 0) {
58
diff = (-1) * diff;
59
}
60
if
(diff < 0.00001) {
61
if
(y1 < 0) {
62
y1 = -y1;
63
}
64
if
(y2 < 0) {
65
y2 = -y2;
66
}
67
if
(y1 < y2) {
68
return
x1;
69
}
else
{
70
return
x2;
71
}
72
}
73
float
x3 = 0, y3 = 0;
74
x3 = x1 - (x1 - x2) * (y1) / (y1 - y2);
75
y3 =
eq
(x3);
76
return
regula_falsi
(x2, x3, y2, y3);
77
}
78
84
void
printRoot
(
float
root,
const
int16_t &count) {
85
if
(count == 1) {
86
std::cout <<
"Your 1st root is : "
<< root << std::endl;
87
}
else
if
(count == 2) {
88
std::cout <<
"Your 2nd root is : "
<< root << std::endl;
89
}
else
if
(count == 3) {
90
std::cout <<
"Your 3rd root is : "
<< root << std::endl;
91
}
else
{
92
std::cout <<
"Your "
<< count <<
"th root is : "
<< root << std::endl;
93
}
94
}
95
}
// namespace false_position
96
}
// namespace numerical_methods
97
102
int
main
() {
103
float
a = 0, b = 0, i = 0, root = 0;
104
int16_t count = 0;
105
float
range =
106
100000;
// Range in which we have to find the root. (-range,range)
107
float
gap = 0.5;
// interval gap. lesser the gap more the accuracy
108
a =
numerical_methods::false_position::eq
((-1) * range);
109
i = ((-1) * range + gap);
110
// while loop for selecting proper interval in provided range and with
111
// provided interval gap.
112
while
(i <= range) {
113
b =
numerical_methods::false_position::eq
(i);
114
if
(b == 0) {
115
count++;
116
numerical_methods::false_position::printRoot
(i, count);
117
}
118
if
(a * b < 0) {
119
root =
numerical_methods::false_position::regula_falsi
(i - gap, i,
120
a, b);
121
count++;
122
numerical_methods::false_position::printRoot
(root, count);
123
}
124
a = b;
125
i += gap;
126
}
127
return
0;
128
}
numerical_methods::false_position::regula_falsi
static float regula_falsi(float x1, float x2, float y1, float y2)
This function finds root of the equation in given interval i.e. (x1,x2).
Definition
false_position.cpp:55
numerical_methods::false_position::eq
static float eq(float x)
This function gives the value of f(x) for given x.
Definition
false_position.cpp:44
numerical_methods::false_position::printRoot
void printRoot(float root, const int16_t &count)
This function prints roots of the equation.
Definition
false_position.cpp:84
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
false_position
Functions for [False Position] (https://en.wikipedia.org/wiki/Regula_falsi) method.
numerical_methods
for assert
numerical_methods
false_position.cpp
Generated by
1.18.0