Monte Carlo Method for Estimating Pi

  • Share this:

Code introduction


This function estimates the value of π to n decimal places using the Monte Carlo method. The Monte Carlo method is a statistical approach that uses random sampling to approximate solutions to mathematical problems.


Technology Stack : Random (random), Mathematical operations (math)

Code Type : Mathematical calculation

Code Difficulty : Intermediate


                
                    
import os
import re
import json
import random
import math
import sys

def calculate_pi_digits(n):
    """估算π的小数点后n位数字。
    
    使用蒙特卡洛方法估算π的值,通过随机点落在单位圆内的概率来逼近π的值。
    
    Args:
        n (int): 要估算的π的小数点后位数。
    
    Returns:
        float: π的近似值。
    """
    inside_circle = 0
    total_points = 0
    
    for _ in range(n * 10**6):  # 使用更多的点来提高精度
        x, y = random.random(), random.random()
        if x**2 + y**2 <= 1.0:
            inside_circle += 1
        total_points += 1
    
    pi_estimate = (inside_circle / total_points) * 4
    return pi_estimate