{ "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": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }