"Completed Buffon’s Needle and Monte Carlo estimation of π"

parent 5daec0a2
{ {
"cells": [], "cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Import the numpy library\n",
"import numpy as np\n",
"# On the Computation of π\n",
"# Buffon's Needle Method\n",
"import numpy as np\n",
"\n",
"# Set a random seed for reproducibility\n",
"np.random.seed(42)\n",
"\n",
"# Number of points to simulate\n",
"n = 1000000 \n",
"\n",
"# Generate random points in the square [-1, 1] x [-1, 1]\n",
"x = np.random.uniform(-1, 1, n)\n",
"y = np.random.uniform(-1, 1, n)\n",
"\n",
"# Check if points are inside the circle\n",
"inside = (x**2 + y**2) <= 1\n",
"\n",
"# Estimate π\n",
"pi_estimate = 4 * np.sum(inside) / n\n",
"print(\"Buffon's Needle π estimate:\", pi_estimate)\n",
"# Monte Carlo Integration Approach\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Generate points and determine those inside the circle\n",
"plt.figure(figsize=(6, 6))\n",
"plt.scatter(x[inside], y[inside], color='blue', alpha=0.5, label='Inside Circle')\n",
"plt.scatter(x[~inside], y[~inside], color='red', alpha=0.5, label='Outside Circle')\n",
"plt.legend()\n",
"plt.title(\"Monte Carlo Method - Points inside/outside the circle\")\n",
"plt.show()\n",
"\n",
"# Final π Estimate\n",
"pi_estimate_mc = 4 * np.sum(inside) / n\n",
"print(\"Monte Carlo π estimate:\", pi_estimate_mc)\n",
"## Conclusion\n",
"Both Buffon’s Needle and Monte Carlo Integration provide useful approximations of π.\n",
"In this case, the estimated value using Monte Carlo is closer to the known value of π ≈ 3.14159.\n"
]
}
],
"metadata": { "metadata": {
"kernelspec": { "kernelspec": {
"display_name": "Python 3", "display_name": "Python 3",
...@@ -16,10 +64,9 @@ ...@@ -16,10 +64,9 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.3" "version": "3.6.4"
} }
}, },
"nbformat": 4, "nbformat": 4,
"nbformat_minor": 2 "nbformat_minor": 2
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment