Skip to content

Instantly share code, notes, and snippets.

@jamesy0ung
Created November 15, 2024 07:38
Show Gist options
  • Save jamesy0ung/91954f23b8f5b102efba9683c2b6764b to your computer and use it in GitHub Desktop.
Save jamesy0ung/91954f23b8f5b102efba9683c2b6764b to your computer and use it in GitHub Desktop.
#include <iostream>
#include <random>
#include <utility>
std::pair<double, double> generateRandomNumber(std::mt19937& gen, std::uniform_real_distribution<>& dis) {
double randomValue1 = dis(gen);
double randomValue2 = dis(gen);
return std::make_pair(randomValue1, randomValue2);
}
bool verifyRandomNumber(std::mt19937& gen, std::uniform_real_distribution<>& dis) {
auto [x, y] = generateRandomNumber(gen, dis);
return ((x * x) + (y * y) <= 1);
}
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0.0, 1.0);
long long int successfulNumbers = 0;
long long int totalNumbers = 0;
long long int currentIterations = 0;
long long int iterations = 100;
while (currentIterations < iterations) {
if (verifyRandomNumber(gen, dis)) {
successfulNumbers++;
}
totalNumbers++;
currentIterations++;
// std::cout << "Sucessful Numbers: " << successfulNumbers << " Total Numbers: " << totalNumbers << " Current iterations: " << currentIterations << std::endl;
}
double piEstimate = 4.0 * successfulNumbers / totalNumbers;
std::cout << "Estimated Pi: " << piEstimate << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment