Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <map>
- #include <cmath>
- using namespace std;
- #define RUNS 2000
- #define PI 3.141592653589793238463
- struct calculation
- {
- int matched;
- int total;
- };
- double makerand()
- {
- return (double)rand() / RAND_MAX;
- }
- double getPi(int matched, int total)
- {
- return 4*(double)matched / total;
- }
- bool checkGoodPrescision(int matched, int total,int prec)
- {
- return floor(getPi(matched,total)*pow(10,prec)) == floor(PI*pow(10,prec));
- }
- int main()
- {
- int matched = 0;
- int total = 0;
- //int prec = 1;
- map<int,calculation> prescitions;
- for(short prec = 1; prec < 10; ++prec)
- {
- //cout << "Prescition is set to " << prec << " decimals" << endl;
- //cout << "Starting calculations"<< endl;
- while(!checkGoodPrescision(matched,total,prec))
- {
- //Loop a few times before we check
- short toSkip = log(total+1)+1;
- for(int i = 0; i < toSkip;++i)
- {
- //if(sqrt(2) * sqrt( pow(makerand(),2) ) <=1)
- if(sqrt( pow(makerand(),2) + pow(makerand(),2) ) <=1)
- ++matched;
- ++total;
- }
- //cout << "\tCurrent iterations: " << total << " pi: " << getPi(matched,total) << endl;
- }
- calculation calc;
- calc.matched = matched;
- calc.total = total;
- prescitions[prec] = calc;
- cout << "###### RESULTS ######" << endl;
- for(auto prec = prescitions.begin(); prec != prescitions.end();++prec)
- {
- cout << "Prescition: " << (*prec).first << endl;
- cout << "\tPi was found to be: " << getPi((*prec).second.matched,(*prec).second.total) << endl;
- cout << "\tIt took " << (*prec).second.total << " iterations. " << (*prec).second.matched << " of them matched" << endl;
- }
- }
- return 0;
- }
- //RESULTS
- Prescition: 1
- Pi was found to be: 3.16667
- It took 24 iterations. 19 of them matched
- Prescition: 2
- Pi was found to be: 3.14504
- It took 131 iterations. 103 of them matched
- Prescition: 3
- Pi was found to be: 3.1411
- It took 163 iterations. 128 of them matched
- Prescition: 4
- Pi was found to be: 3.1415
- It took 329683 iterations. 258925 of them matched
- Prescition: 5
- Pi was found to be: 3.1416
- It took 329891 iterations. 259096 of them matched
- Prescition: 6
- Pi was found to be: 3.14159
- It took 329904 iterations. 259106 of them matched
- Prescition: 7
- Pi was found to be: 3.14159
- It took 353161 iterations. 277372 of them matched
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement