使用蒙特卡罗方法(Monte Carlo Method)来估算圆周率的值
import random
生成的随机点数量
num_points = 1000000
落在圆内的点的数量
inside_circle = 0
for _ in range(num_points):# 生成[-1, 1]范围内的随机坐标x = random.uniform(-1, 1)y = random.uniform(-1, 1)# 判断点是否在圆内(根据圆的方程 x^2 + y^2 <= 1)if x ** 2 + y ** 2 <= 1:inside_circle += 1
估算圆周率
pi_estimate = 4 * inside_circle / num_points
print(pi_estimate)
public class PiEstimation { public static void main(String[] args) { int numPoints = 1000000; int insideCircle = 0; for (int i = 0; i < numPoints; i++) { double x = Math.random() * 2 - 1; double y = Math.random() * 2 - 1; if (x * x + y * y <= 1) { insideCircle++; } } double piEstimate = 4.0 * insideCircle / numPoints; System.out.println(piEstimate); } }
#include <iostream> #include <ctime> #include <cstdlib> int main() { const int numPoints = 1000000; int insideCircle = 0; srand(static_cast<unsigned int>(time(nullptr))); for (int i = 0; i < numPoints; ++i) { double x = static_cast<double>(rand()) / RAND_MAX * 2 - 1; double y = static_cast<double>(rand()) / RAND_MAX * 2 - 1; if (x * x + y * y <= 1) { insideCircle++; } } double piEstimate = 4.0 * insideCircle / numPoints; std::cout << piEstimate << std::endl; return 0; }