Created
November 17, 2020 08:25
-
-
Save consoleaf/ed8897f711465658ac839f13444f3fcc to your computer and use it in GitHub Desktop.
This file contains 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 <ctime> | |
#include <future> | |
#include <iostream> | |
#include <thread> | |
using namespace std; | |
#define EPSILON 1e-5 | |
#define ASYNCMODE | |
#define DELAY | |
double f1(double x) { return 1 / x; } | |
double f2(double x) { return x; } | |
double f3(double x) { return 1 / x; } | |
double f4(double x) { return 1 / x; } | |
double f5(double x) { return 1 / x; } | |
double quad(double left, double right, double fleft, double fright, | |
double lrarea, double f(double)) { | |
#ifdef DELAY | |
std::chrono::milliseconds timespan(1); // or whatever | |
std::this_thread::sleep_for(timespan); | |
#endif | |
double mid = (left + right) / 2; | |
double fmid = f(mid); | |
double larea = (fleft + fmid) * (mid - left) / 2; | |
double rarea = (fmid + fright) * (right - mid) / 2; | |
if (abs(larea + rarea - lrarea) > EPSILON) { | |
#ifdef ASYNCMODE | |
future<double> larea_promise = async(&quad, left, mid, fleft, fmid, larea, f); | |
future<double> rarea_promise = | |
async(&quad, mid, right, fmid, fright, rarea, f); | |
larea = larea_promise.get(); | |
rarea = rarea_promise.get(); | |
#else | |
larea = quad(left, mid, fleft, fmid, larea); | |
rarea = quad(mid, right, fmid, fright, rarea); | |
#endif | |
} | |
return rarea + larea; | |
} | |
double quad(double left, double right, double f(double)) { | |
return quad(left, right, f(left), f(right), (f(left) + f(right)) * (right - left) / 2, f); | |
} | |
int main(int argc, char *argv[]) { | |
double a, b; | |
a = 1; | |
b = 1e9; | |
#ifdef ASYNCMODE | |
cerr << "Async..." << endl; | |
#else | |
cerr << "Single thread..." << endl; | |
#endif | |
cout << quad(a, b, f1) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment