Skip to content

Instantly share code, notes, and snippets.

@proelbtn
Created May 17, 2019 04:02
Show Gist options
  • Save proelbtn/b95afbdf15691cad469ca42dc5902dcb to your computer and use it in GitHub Desktop.
Save proelbtn/b95afbdf15691cad469ca42dc5902dcb to your computer and use it in GitHub Desktop.
#include <iomanip>
#include <iostream>
#include <functional>
#include <limits>
typedef std::function<double(double)> func_t;
double bisection_method(func_t f, double min, double max) {
double mid;
double minval, midval, maxval;
while ((max - min) > std::numeric_limits<double>::epsilon()) {
minval = f(min); maxval = f(max);
mid = (max + min) / 2; midval = f(mid);
min = (minval * midval > 0) ? mid : min;
max = (midval * maxval > 0) ? mid : max;
}
return (max + min) / 2;
}
double false_position_method(func_t f, double min, double max) {
double mid;
double minval, midval, maxval;
while ((max - min) > std::numeric_limits<double>::epsilon()) {
minval = f(min); maxval = f(max);
mid = (max * minval - min * maxval) / (minval - maxval); midval = f(mid);
min = (minval * midval >= 0) ? mid : min;
max = (midval * maxval >= 0) ? mid : max;
}
return (max + min) / 2;
}
int main() {
double ans;
func_t f = [](double x) { return x * x - 2; };
std::cout << std::setprecision(100);
ans = bisection_method(f, 0, 2);
std::cout << "bisection method: ";
std::cout << ans << std::endl;
ans = false_position_method(f, 0, 2);
std::cout << "false position method: ";
std::cout << ans << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment