From 11e725e583e107a9f261f28e0bd24c35ed0da8d9 Mon Sep 17 00:00:00 2001 From: d0fb1445df0f93dc28c67893dfa732c9 Date: Mon, 26 Dec 2022 17:08:17 +0000 Subject: [PATCH] par1 --- module2/exo1/toy_notebook_en.ipynb | 52 ++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/module2/exo1/toy_notebook_en.ipynb b/module2/exo1/toy_notebook_en.ipynb index 84ddd87..56a0275 100644 --- a/module2/exo1/toy_notebook_en.ipynb +++ b/module2/exo1/toy_notebook_en.ipynb @@ -1,8 +1,23 @@ { "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 1 On the computation of π" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Asking the maths library\n", + "My computer tells me that $\\pi$ is *approximatively*" + ] + }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 7, "metadata": {}, "outputs": [ { @@ -18,9 +33,17 @@ "print(pi)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Buffon's needle\n", + "Applying the method of [Buffon's needle](https://en.wikipedia.org/wiki/Buffon%27s_needle_problem), we get the __approximation__" + ] + }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 8, "metadata": {}, "outputs": [ { @@ -29,7 +52,7 @@ "3.128911138923655" ] }, - "execution_count": 3, + "execution_count": 8, "metadata": {}, "output_type": "execute_result" } @@ -43,9 +66,17 @@ "2/(sum((x+np.sin(theta))>1)/N)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using a surface fraction argument\n", + "A method that is easier to understand and does not make use of the $\\sin$ function is based on the fact that if $X\\sim U(0,1)$ and $Y\\sim U(0,1)$, then $P[X^2+Y^2\\leq 1] = \\pi/4$ (see [\"Monte Carlo method\" on Wikipedia](https://en.wikipedia.org/wiki/Monte_Carlo_method)). The following code uses this approach:" + ] + }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -64,6 +95,7 @@ "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", + "\n", "np.random.seed(seed=42)\n", "N = 1000\n", "x = np.random.uniform(size=N, low=0, high=1)\n", @@ -71,15 +103,23 @@ "\n", "accept = (x*x+y*y) <= 1\n", "reject = np.logical_not(accept)\n", + "\n", "fig, ax = plt.subplots(1)\n", "ax.scatter(x[accept], y[accept], c='b', alpha=0.2, edgecolor=None)\n", "ax.scatter(x[reject], y[reject], c='r', alpha=0.2, edgecolor=None)\n", "ax.set_aspect('equal')" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It is then straightforward to obtain a (not really good) approximation to $\\pi$ by counting how many times, on average, $X^2 + Y^2$ is smaller than 1:" + ] + }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 11, "metadata": {}, "outputs": [ { @@ -88,7 +128,7 @@ "3.112" ] }, - "execution_count": 5, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } -- 2.18.1