Created
March 4, 2017 01:11
-
-
Save epsilon-phase/51e619da2581c13593528fba73177aa8 to your computer and use it in GitHub Desktop.
Pi day code
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 <iostream> | |
#include <iomanip> | |
#include <cmath> | |
#include <random> | |
#include <tuple> | |
#include <functional> | |
const double PI=3.14159265359; | |
bool within_circle(double radius,double x,double y){ | |
return std::hypot(x,y)<radius; | |
} | |
template<typename Y> double proportion_succeded(long n,std::function<bool(Y)>& p, std::function<Y()>& g){ | |
double dn=n; | |
double succ=0; | |
for(size_t i=0;i<n;i++) | |
if(p(g())) | |
succ+=1/dn; | |
return succ; | |
} | |
void calculate_pi(int min_sample_exp,int max_sample_exp,int min_radius_exp,int max_radius_exp){ | |
double radius=1; | |
long samples=1; | |
std::default_random_engine en; | |
std::uniform_real_distribution<double> gen(0.0,radius); | |
std::function<bool(std::tuple<double,double>)> pred= | |
[&](std::tuple<double,double> p){return within_circle(radius,std::get<0>(p),std::get<1>(p));}; | |
std::function<std::tuple<double,double>()> point_gen= | |
[&]()->std::tuple<double,double>{return std::make_tuple<double,double>(gen(en),gen(en));}; | |
for(int m=min_sample_exp;m<max_sample_exp;m++) | |
std::cout<<std::setw(5)m<<"\t"; | |
std::cout<<"\n"; | |
std::vector<std::future<double>> | |
for(int n=min_radius_exp;n<=max_radius_exp;n++){ | |
//update the generator's maximum | |
radius=std::pow(10,n); | |
gen=std::uniform_real_distribution<double>(0,radius); | |
for(int m=min_sample_exp;m<=max_sample_exp;m++){ | |
samples=std::pow(10,m); | |
//run the samples | |
double temp=proportion_succeded(samples, | |
pred, | |
point_gen)*4; | |
//show the absolute difference between the calculated value and PI | |
std::cout<<std::setw(5)<<std::abs(temp-PI)<<std::setw(5)<<"\t"; | |
} | |
std::cout<<"\n"<<std::flush; | |
} | |
} | |
int main(){ | |
calculate_pi(0,9,0,7); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment