Skip to content

Instantly share code, notes, and snippets.

@yao2030
Created June 21, 2014 04:58
Show Gist options
  • Save yao2030/41bbe278b54a9447ed69 to your computer and use it in GitHub Desktop.
Save yao2030/41bbe278b54a9447ed69 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
const double EPS = 1e-6;
inline double f(double x) { return x * x * x - 5 * x * x + 10 * x - 80; }
int main(void) {
double root, x1 = 0, x2 = 100, y = 0.0;
root = x1 + (x2 - x1) / 2;
int triedTimes = 1;
y = f(root);
while (fabs(y) > EPS) {
if (y > 0)
x2 = root;
else
x1 = root;
root = x1 + (x2 - x1) / 2;
triedTimes++;
y = f(root);
}
cout << setprecision(10) << root << endl;
cout << triedTimes << endl;
return 0;
}
@yao2030
Copy link
Author

yao2030 commented Jun 21, 2014

get root of an equation using binary search.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment