Programming of Buffon’s needle problem without using the number, \pi!

Buffon’s needle problem without $\pi$
1. Estimate $\pi$ with hit-or-method with samples
2. Run algorithm for solving Buffon’s needle problem with the estimate

import pandas as pd
import random

n_lists = [100000000]

# Lists to store results
results = []
d = 2
# Monte Carlo simulation
for n in n_lists:
    total_frequencies = 0
    for _ in range(n):
        x_i = random.random()* d - 1
        y_i = random.random()* d - 1


        if x_i**2 + y_i**2 <= 1:
            total_frequencies += 1

    pi_hat_n = total_frequencies / n * 4

pi_hat_hit_or_method = results[0][1]
print(f"estimate of pi by hit-or-method: {pi_hat_hit_or_method}")
import pandas as pd
import math
# Given values
l = 1
d = 2
pi_ = pi_hat_hit_or_method

n_lists = [10, 100, 1000,10000, 100000,1000000,10000000, 100000000]

# Lists to store results
results = []

# Monte Carlo simulation
for n in n_lists:
    total_frequencies = 0
    for _ in range(n):
        C_i = random.random() * d
        Theta_i = random.random() * pi_

        if C_i + math.sin(Theta_i) > d:
            total_frequencies += 1

    p_hat_n = total_frequencies / n
    pi_hat_n = 1 / p_hat_n if p_hat_n > 0 else float('inf')  # Avoid division by zero

    results.append([n, pi_hat_n])

# Create DataFrame with proper column names for LaTeX rendering
df = pd.DataFrame(results, columns=["n", "Estimate of π"])

df_buffon = df

df_buffon

Leave a Comment