TheAlgorithms-C-Plus-Plus/computer_oriented_statistical_methods/Bisection_method.CPP

41 lines
814 B
C++
Raw Normal View History

#include <cmath>
#include <iostream>
2016-10-08 18:10:36 +08:00
float eq(float i) {
return (std::pow(i, 3) - (4 * i) - 9); // original equation
2016-10-08 18:10:36 +08:00
}
int main() {
float a, b, x, z;
2016-10-08 18:10:36 +08:00
for (int i = 0; i < 100; i++) {
z = eq(i);
if (z >= 0) {
b = i;
a = --i;
break;
}
}
2016-10-08 18:10:36 +08:00
std::cout << "\nFirst initial: " << a;
std::cout << "\nSecond initial: " << b;
for (int i = 0; i < 100; i++) {
x = (a + b) / 2;
z = eq(x);
std::cout << "\n\nz: " << z << "\t[" << a << " , " << b
<< " | Bisect: " << x << "]";
2016-10-08 18:10:36 +08:00
if (z < 0) {
a = x;
} else {
b = x;
}
2016-10-08 18:10:36 +08:00
if (z > 0 && z < 0.0009) // stoping criteria
break;
}
2016-10-08 18:10:36 +08:00
std::cout << "\n\nRoot: " << x;
return 0;
2016-10-08 18:10:36 +08:00
}