Created
July 4, 2020 13:44
-
-
Save niklasbuschmann/ba594ccac39b51611c789993e3672685 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
bool signchange (double a, double b) { | |
return (a > 0 && b < 0) || (a < 0 && b > 0); | |
} | |
string bisection(double a, double b, double epsilon_x, double epsilon_y, double (*f)(double), int n) { | |
double average = (a + b) / 2.0; | |
if (!signchange(f(a), f(b))) | |
return "Error: no change of sign"; | |
cout << "step: " << n << " interval: [" << a << ", " << b << "] f(" << average << "): " << f(average) << endl; | |
if (abs(a - b) < epsilon_x || abs(f(average)) < epsilon_y) | |
return "root: " + to_string(average); | |
if (signchange(f(a), f(average))) | |
return bisection(a, average, epsilon_x, epsilon_y, f, n + 1); | |
if (signchange(f(average), f(b))) | |
return bisection(average, b, epsilon_x, epsilon_y, f, n + 1); | |
} | |
double f(double x) { | |
// return cos(x) - x; | |
return exp(x) - pow(x, 3); | |
} | |
int main() { | |
double a, b; | |
cout << "x0: "; | |
cin >> a; | |
cout << "x1: "; | |
cin >> b; | |
cout << bisection(a, b, pow(10, -4), pow(10, -3), &f, 1) << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment