# 2025 Spring, Montecarlo methods and its applications ##Homework 3 Hit-or-miss method ### Seonggyu Lee #### 2025.03.24
Let $(x_i,y_i)$ be i-th random samples with $x_i \sim U[-1,1], y_i \sim U[-1,1]$ where $ 1 \leq i \leq n$.
Let $\hat{\pi}_n = \frac{\sum_{i=1}^n \mathbf{1}(x_i^2 +y_i^2 \leq 1)}{n} \times 4$.
I set $n\in \{10, 100, 1000,10000, 100000,1000000,10000000, 100000000\}$ and evaluated $\pi_n$ and compared its results to the method used for Buffon’s needle.
import pandas as pd
import random
n_lists = [10,100,1000,10000,100000,1000000,10000000, 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
results.append([n, pi_hat_n])
# Create DataFrame with proper column names for LaTeX rendering
df = pd.DataFrame(results, columns=["n", "Estimate of π"])
df_hit_or_miss = df
print(df_buffon)
print(df_hit_or_miss)
n Estimate of π
0 10 2.500000
1 100 3.571429
2 1000 3.389831
3 10000 3.054368
4 100000 3.121099
5 1000000 3.147564
6 10000000 3.145419
7 100000000 3.142076
n Estimate of π
0 10 2.400000
1 100 2.960000
2 1000 3.140000
3 10000 3.146000
4 100000 3.139120
5 1000000 3.145176
6 10000000 3.142128
7 100000000 3.141740
df_combined = pd.concat([df_buffon, df_hit_or_miss], axis=1)
df_combined.columns=['n', "Results of Buffon's needle", "removing", 'Results of Hit-or-miss method']
df_comparison = df_combined[['n',"Results of Buffon's needle",'Results of Hit-or-miss method' ]]
df_comparison
n Results of Buffon’s needle Results of Hit-or-miss method
0 10 2.500000 2.400000
1 100 3.571429 2.960000
2 1000 3.389831 3.140000
3 10000 3.054368 3.146000
4 100000 3.121099 3.139120
5 1000000 3.147564 3.145176
6 10000000 3.145419 3.142128
7 100000000 3.142076 3.141740