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. auto start = std::chrono::high_resolution_clock::now();
  23. double pi_estimate = monte_carlo_simulation(iterations);
  24. auto end = std::chrono::high_resolution_clock::now();
  25.  
  26. std::cout << "Estimación de Pi: " << pi_estimate << "\n";
  27. std::cout << "Tiempo de ejecución: "
  28. << std::chrono::duration<double>(end - start).count() << " segundos\n";
  29.  
  30. return 0;
  31. }
  32.  
Success #stdin #stdout 0.02s 5284KB
stdin
Standard input is empty
stdout
Estimación de Pi: 3.1396
Tiempo de ejecución: 0.0199699 segundos