fork download
  1. #include <iostream>
  2. #include <random>
  3. #include <chrono>
  4.  
  5. double monte_carlo_simulation(int iterations) {
  6. std::default_random_engine generator;
  7. std::uniform_real_distribution<double> distribution(0.0, 1.0);
  8.  
  9. int inside_circle = 0;
  10. for (int i = 0; i < iterations; ++i) {
  11. double x = distribution(generator);
  12. double y = distribution(generator);
  13. if (x * x + y * y <= 1) {
  14. ++inside_circle;
  15. }
  16. }
  17. return 4.0 * inside_circle / iterations;
  18. }
  19.  
  20. int main() {
  21. int iterations = 1000000;
  22.  
  23. auto start = std::chrono::high_resolution_clock::now();
  24. double pi_estimate = monte_carlo_simulation(iterations);
  25. auto end = std::chrono::high_resolution_clock::now();
  26.  
  27. std::cout << "EstimaciĆ³n de Pi: " << pi_estimate << "\n";
  28. std::cout << "Tiempo de ejecuciĆ³n: "
  29. << std::chrono::duration<double>(end - start).count() << " segundos\n";
  30.  
  31. return 0;
  32. }
  33.  
Success #stdin #stdout 0.02s 5260KB
stdin
Standard input is empty
stdout
Estimación de Pi: 3.1396
Tiempo de ejecución: 0.0200109 segundos