Created
July 10, 2017 17:30
-
-
Save dllu/2433300be8159c796139732a8542c60f to your computer and use it in GitHub Desktop.
Generate uniform random points in a unit disk using two methods
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 <cmath> | |
#include <iostream> | |
#include <random> | |
#include <vector> | |
#include <chrono> | |
using namespace std; | |
template <typename T> | |
vector<pair<double, double>> tinybrain(const int n, | |
uniform_real_distribution<double> &unif, | |
T &engine) { | |
vector<pair<double, double>> points(n); | |
for (auto &p : points) { | |
while (true) { | |
double x = unif(engine); | |
double y = unif(engine); | |
if (x * x + y * y <= 1.0) { | |
p = make_pair(x, y); | |
break; | |
} | |
} | |
} | |
return points; | |
} | |
template <typename T> | |
vector<pair<double, double>> smallbrain(const int n, | |
uniform_real_distribution<double> &unif_r, | |
uniform_real_distribution<double> &unif_t, | |
T &engine) { | |
vector<pair<double, double>> points(n); | |
for (auto &p : points) { | |
double rho = unif_r(engine); | |
double t = unif_t(engine); | |
double r = sqrt(rho); | |
double x = r * sin(t); | |
double y = r * cos(t); | |
p = make_pair(x, y); | |
} | |
return points; | |
} | |
int main() { | |
random_device rd; | |
mt19937 engine(rd()); | |
uniform_real_distribution<double> uniform_dist_1_1(-1.0, 1.0); | |
uniform_real_distribution<double> uniform_dist_0_1(0.0, 1.0); | |
uniform_real_distribution<double> uniform_dist_0_2pi(0.0, 2.0 * M_PI); | |
const int n = 100000000; | |
auto start = chrono::steady_clock::now(); | |
vector<pair<double, double>> tinybrain_out = | |
tinybrain(n, uniform_dist_1_1, engine); | |
auto end = chrono::steady_clock::now(); | |
chrono::duration<double> elapsed = end - start; | |
cout << "tiny brain: " << elapsed.count() << " seconds" << endl; | |
start = chrono::steady_clock::now(); | |
vector<pair<double, double>> smallbrain_out = | |
smallbrain(n, uniform_dist_0_1, uniform_dist_0_2pi, engine); | |
end = chrono::steady_clock::now(); | |
elapsed = end - start; | |
cout << "small brain: " << elapsed.count() << " seconds" << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment