SHARE
TWEET

generate pi ( dartboard method )

a guest Mar 24th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "pch.h"    // default
  2. #include <random>   // for random
  3. #include <math.h>   // for sqrt
  4. #include <iostream> // output
  5.  
  6. double radius = 500;
  7.  
  8. int random_int(int min, int max)    // pesudo random
  9. {
  10.     std::random_device seeder;
  11.     std::mt19937 engine(seeder());
  12.     std::uniform_int_distribution<int> dist(min, max);
  13.     return dist(engine);
  14. }
  15.  
  16. int main()
  17. {
  18.     // variables
  19.     int total_dots = 0;
  20.     int dots_in = 0;
  21.     double pi = 0;
  22.  
  23.     while (1)   // loop
  24.     {
  25.         for (int i = 0; i < 10000; i++) // do 10,000 times before refreshing console output
  26.         {
  27.             double point_x = (double)(random_int(radius*-1, radius));
  28.             double point_y = (double)(random_int(radius*-1, radius));
  29.  
  30.             total_dots++;               // add onto total dots (in our invisible drawing)
  31.  
  32.             if (point_x < 0)            // make points positive to deal w/ errors
  33.                 point_x *= -1;
  34.             if (point_y < 0)
  35.                 point_y *= -1;
  36.  
  37.                                         // pythagorean theorem
  38.             double distance = sqrt(point_x * point_x + point_y * point_y);
  39.  
  40.             if (distance < radius)
  41.                 dots_in++;
  42.         }
  43.        
  44.         pi = 4 * (double(dots_in) / double(total_dots));
  45.         std::cout << pi << std::endl;
  46.     }
  47. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top