{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "91cc6b49",
   "metadata": {},
   "source": [
    "# Practical 1 — My first Monte Carlo (Worksheet)\n",
    "\n",
    "*Dynamic optimisation and Monte Carlo simulation in Python* — M2 IF & MIA, Université Sorbonne Paris Nord.\n",
    "Session 1, “Computing with chance”. Time: about an hour and a half, then challenges for those who are quick.\n",
    "\n",
    "**Goal.** Redo the experiments of video 1 yourself, line by line: the coin, π with darts, the bell curve of the\n",
    "estimates that narrows, the confidence interval that “catches” the true value 95 times out of a hundred, and the\n",
    "price of a call option compared with its judge, the Black–Scholes formula.\n",
    "\n",
    "**Rules of the game.**\n",
    "\n",
    "- NumPy only for the computations (and matplotlib for the figures); a single generator, `np.random.default_rng(seed)`.\n",
    "- Predict, simulate, verify: before each experiment, write down what you expect; then simulate; then compare.\n",
    "- Colour code of the course: **blue = simulated**, **orange = exact (the judge)**, **red = failure**, **grey = everything else**.\n",
    "- The cells marked `# TO COMPLETE` are for you to fill in. The notebook runs even when incomplete: the checks\n",
    "  print “to complete” as long as the answer is missing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55129320",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Colour code of the course (the same as in the videos, the course notes and the slides)\n",
    "BLUE, ORANGE, RED, GREY = \"#5B9CFF\", \"#FFA14A\", \"#FF6B66\", \"#5F6C84\"\n",
    "plt.rcParams.update({\n",
    "    \"figure.figsize\": (7.5, 3.6), \"figure.dpi\": 100, \"axes.grid\": True, \"grid.color\": \"#E4E9F1\",\n",
    "    \"axes.spines.top\": False, \"axes.spines.right\": False, \"axes.edgecolor\": \"#9AA8BF\",\n",
    "    \"axes.titlelocation\": \"left\", \"axes.titleweight\": \"bold\", \"font.size\": 10,\n",
    "    \"axes.prop_cycle\": plt.cycler(color=[BLUE, ORANGE, RED, GREY]),\n",
    "})\n",
    "\n",
    "\n",
    "def ready(*objects):\n",
    "    \"\"\"True if every object has been computed (neither None nor NaN): the notebook runs even when incomplete.\"\"\"\n",
    "    for o in objects:\n",
    "        if o is None or o is Ellipsis:\n",
    "            return False\n",
    "        try:\n",
    "            if np.any(np.isnan(np.asarray(o, dtype=float))):\n",
    "                return False\n",
    "        except (TypeError, ValueError):\n",
    "            pass\n",
    "    return True\n",
    "\n",
    "\n",
    "def check(name, value, expected, tol):\n",
    "    \"\"\"Compare a value with what is expected (to within tol), without ever interrupting the notebook.\"\"\"\n",
    "    if not ready(value):\n",
    "        print(f\"… {name}: to complete\")\n",
    "    elif abs(float(value) - expected) <= tol:\n",
    "        print(f\"✓ {name} = {float(value):.6g} (expected ≈ {expected:.6g})\")\n",
    "    else:\n",
    "        print(f\"✗ {name} = {float(value):.6g}, expected ≈ {expected:.6g} (to within ± {tol:g}): review your code\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4ccd579",
   "metadata": {},
   "source": [
    "## 1. Reproducible randomness (10 min)\n",
    "\n",
    "A computer does not toss coins: it computes a sequence of numbers that *behave* like chance. NumPy's generator\n",
    "(`default_rng`, PCG64 algorithm) is entirely deterministic: **same seed, same sequence**. This is what makes a\n",
    "simulation verifiable by someone else.\n",
    "\n",
    "**1.1** Create two generators with the same seed 2026, draw five uniform numbers on [0, 1) with each, and compare.\n",
    "Then draw five more numbers with the first one: are they equal to the first five?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d06de28",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TO COMPLETE: two generators with seed 2026, five draws each\n",
    "g1 = None\n",
    "g2 = None"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00cc0361",
   "metadata": {},
   "source": [
    "**1.2** Write `tosses(n, rng)`, which returns an array of `n` coin tosses (1 = heads, 0 = tails), deciding that a\n",
    "uniform number below 1/2 is heads. As in the video: `heads = rng.random(n) < 0.5`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf2e17d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "def tosses(n, rng):\n",
    "    \"\"\"n tosses of a fair coin: array of 0s (tails) and 1s (heads).\"\"\"\n",
    "    # TO COMPLETE\n",
    "    return None\n",
    "\n",
    "\n",
    "rng = np.random.default_rng(2)\n",
    "ten = tosses(10, rng)\n",
    "print(\"ten tosses:\", ten)\n",
    "if ready(ten):\n",
    "    check(\"proportion of heads in a million tosses\", tosses(1_000_000, np.random.default_rng(2)).mean(), 0.5, 0.002)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d72afa5",
   "metadata": {},
   "source": [
    "## 2. The law of large numbers, and what it does not say (15 min)\n",
    "\n",
    "**Predict.** In ten tosses, what is the probability of getting *exactly* five heads? Write down your answer.\n",
    "\n",
    "**2.1** Simulate 10,000 series of 10 tosses (an array of shape `(10_000, 10)`), count the heads in each series and\n",
    "estimate the probability of getting exactly 5 heads. Compare with the exact value $\\binom{10}{5}/2^{10}$\n",
    "(`math.comb(10, 5) / 2**10`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01bf559a",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(10)\n",
    "# TO COMPLETE: n_heads = number of heads in each of the 10,000 series; p5 = proportion of series with 5 heads\n",
    "n_heads = None\n",
    "p5 = None\n",
    "p5_exact = math.comb(10, 5) / 2**10\n",
    "check(\"P(5 heads in 10), simulated\", p5, p5_exact, 0.015)\n",
    "\n",
    "if ready(n_heads):\n",
    "    k = np.arange(11)\n",
    "    exact = np.array([math.comb(10, j) for j in k]) / 2**10\n",
    "    simulated = np.bincount(n_heads, minlength=11) / len(n_heads)\n",
    "    fig, ax = plt.subplots()\n",
    "    ax.bar(k, simulated, width=0.6, color=BLUE, label=\"simulated (10,000 series)\")\n",
    "    ax.scatter(k, exact, color=ORANGE, zorder=3, s=40, marker=\"_\", linewidths=3, label=\"exact: C(10, k) / 1024\")\n",
    "    ax.set_xticks(k)\n",
    "    ax.set_xlabel(\"number of heads in 10 tosses\")\n",
    "    ax.set_ylabel(\"probability\")\n",
    "    ax.set_title(\"Exactly 5 heads: less than a quarter of the time\")\n",
    "    ax.legend()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "095c110a",
   "metadata": {},
   "source": [
    "**2.2** Toss the coin a million times. After each toss $n$, compute the proportion of heads\n",
    "$\\hat p_n = k_n / n$ and the gap $k_n - (n - k_n)$ between heads and tails (hint: `np.cumsum`). Plot both\n",
    "curves as functions of $n$ (logarithmic horizontal axis), with the orange line $1/2$ for the proportion and the\n",
    "grey band $\\pm\\sqrt n$ for the gap.\n",
    "\n",
    "**Predict.** Does the gap heads − tails come back towards zero as $n$ grows?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91a832b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(2)\n",
    "n = np.arange(1, 1_000_001)\n",
    "# TO COMPLETE: proportion[i] = proportion of heads after i+1 tosses; gap[i] = heads − tails after i+1 tosses\n",
    "proportion = None\n",
    "gap = None\n",
    "\n",
    "if ready(proportion, gap):\n",
    "    print(f\"after 10,000 tosses: {proportion[9_999]:.4%}; after a million: {proportion[-1]:.4%}\")\n",
    "    print(f\"gap heads − tails after a million tosses: {gap[-1]:+d}\")\n",
    "    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 3.6))\n",
    "    a1.semilogx(n, proportion, color=BLUE, lw=1)\n",
    "    a1.axhline(0.5, color=ORANGE, lw=2)\n",
    "    a1.set_ylim(0.3, 0.7)\n",
    "    a1.set_title(\"The proportion settles down\")\n",
    "    a1.set_xlabel(\"number of tosses n\")\n",
    "    a2.semilogx(n, gap, color=BLUE, lw=1)\n",
    "    a2.fill_between(n, -np.sqrt(n), np.sqrt(n), color=GREY, alpha=0.2, lw=0, label=\"± √n\")\n",
    "    a2.axhline(0, color=GREY, lw=1)\n",
    "    a2.set_title(\"The gap heads − tails does not come back to zero\")\n",
    "    a2.set_xlabel(\"number of tosses n\")\n",
    "    a2.legend(loc=\"upper left\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eeb6e14e",
   "metadata": {},
   "source": [
    "## 3. π with darts (20 min)\n",
    "\n",
    "We throw $n$ uniform points into the square $[0,1]^2$. The proportion of points that land in the quarter disc\n",
    "$x^2 + y^2 \\le 1$ estimates its area, $\\pi/4$; so $4 \\times$ proportion estimates $\\pi$.\n",
    "\n",
    "**3.1** Write `estimate_pi(n, rng)`, then draw 3,200 darts: in blue those in the quarter disc, in grey the others,\n",
    "and the arc in orange."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "812bd6b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def estimate_pi(n, rng):\n",
    "    \"\"\"Estimate of π from n uniform darts in the unit square.\"\"\"\n",
    "    # TO COMPLETE\n",
    "    return None\n",
    "\n",
    "\n",
    "check(\"estimate_pi(1_000_000)\", estimate_pi(1_000_000, np.random.default_rng(21)), math.pi, 0.01)\n",
    "\n",
    "rng = np.random.default_rng(21)\n",
    "x, y = rng.random(3200), rng.random(3200)\n",
    "inside = x * x + y * y <= 1\n",
    "t = np.linspace(0, math.pi / 2, 300)\n",
    "fig, ax = plt.subplots(figsize=(4.6, 4.6))\n",
    "ax.scatter(x[inside], y[inside], s=4, color=BLUE)\n",
    "ax.scatter(x[~inside], y[~inside], s=4, color=GREY)\n",
    "ax.plot(np.cos(t), np.sin(t), color=ORANGE, lw=2.5)\n",
    "ax.set_aspect(\"equal\")\n",
    "ax.set_xlim(0, 1)\n",
    "ax.set_ylim(0, 1)\n",
    "ax.set_title(f\"{inside.sum()} / 3,200 in the quarter disc → π ≈ {4 * inside.mean():.4f}\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "344635fc",
   "metadata": {},
   "source": [
    "**3.2** Follow the estimate as the number of points grows up to a million (hint: the cumulative mean of the\n",
    "indicator `inside`). Plot it (logarithmic horizontal axis) with the orange line $\\pi$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91c1417f",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(1812)\n",
    "N = 1_000_000\n",
    "n = np.arange(1, N + 1)\n",
    "# TO COMPLETE: estimate[i] = estimate of π with the first i+1 points\n",
    "estimate = None\n",
    "\n",
    "if ready(estimate):\n",
    "    for m in (100, 10_000, 1_000_000):\n",
    "        print(f\"n = {m:>9,}: π ≈ {estimate[m - 1]:.5f}   (error {estimate[m - 1] - math.pi:+.5f})\")\n",
    "    fig, ax = plt.subplots()\n",
    "    ax.semilogx(n, estimate, color=BLUE, lw=1)\n",
    "    ax.axhline(math.pi, color=ORANGE, lw=2)\n",
    "    ax.set_ylim(2.9, 3.4)\n",
    "    ax.set_xlabel(\"number of points n\")\n",
    "    ax.set_title(\"The digits arrive, more and more slowly\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d32b74d",
   "metadata": {},
   "source": [
    "## 4. The bell curve narrows (25 min)\n",
    "\n",
    "The estimate of π is itself **drawn at random**: redo the experiment and you get another number. To measure its\n",
    "error, we repeat it $R$ times and look at the shape of the results.\n",
    "\n",
    "**Predict.** If we take four times as many points, does the bell curve of the estimates become four times\n",
    "narrower? Twice? Sixteen times?\n",
    "\n",
    "**4.1** Write `repeat(n, R, rng)`, which returns an array of $R$ independent estimates of π, each with $n$\n",
    "points (a loop over $R$ is enough)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70b15d78",
   "metadata": {},
   "outputs": [],
   "source": [
    "def repeat(n, R, rng):\n",
    "    \"\"\"R independent estimates of π, each with n points.\"\"\"\n",
    "    # TO COMPLETE\n",
    "    return None\n",
    "\n",
    "\n",
    "rng = np.random.default_rng(1812)\n",
    "sizes = [100, 400, 1600, 6400]\n",
    "bells = {n: repeat(n, 2000, rng) for n in sizes}\n",
    "if ready(*bells.values()):\n",
    "    fig, ax = plt.subplots()\n",
    "    shades = [\"#C9DCFF\", \"#9DC0FF\", \"#78A9FF\", BLUE]\n",
    "    for n, c in zip(sizes, shades):\n",
    "        ax.hist(bells[n], bins=np.linspace(2.6, 3.7, 89), color=c, alpha=0.9, label=f\"n = {n}\")\n",
    "    ax.axvline(math.pi, color=ORANGE, lw=2)\n",
    "    ax.set_xlabel(\"estimate of π\")\n",
    "    ax.set_title(\"× 4 points: the bell curve narrows\")\n",
    "    ax.legend()\n",
    "    plt.show()\n",
    "    for n in sizes:\n",
    "        print(f\"n = {n:>5}: standard deviation of the 2,000 estimates = {bells[n].std(ddof=1):.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f6c21c9",
   "metadata": {},
   "source": [
    "**4.2** Plot the standard deviation of the estimates as a function of $n$ on a log-log scale and measure the slope\n",
    "by a regression (`np.polyfit(np.log(n), np.log(std_dev), 1)`). Compare with the prediction $\\sigma/\\sqrt n$ with\n",
    "$\\sigma = 4\\sqrt{p(1-p)}$ and $p = \\pi/4$: this is the standard deviation of **one** dart (multiplied by 4)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e1b09a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "sigma = 4 * math.sqrt(math.pi / 4 * (1 - math.pi / 4))\n",
    "print(f\"σ of one dart: {sigma:.4f}\")\n",
    "# TO COMPLETE: std_devs = array of the measured standard deviations; slope = slope of the log-log line\n",
    "nn = np.array(sizes)\n",
    "std_devs = None\n",
    "slope = None\n",
    "check(\"log-log slope\", slope, -0.5, 0.05)\n",
    "\n",
    "if ready(std_devs):\n",
    "    fig, ax = plt.subplots()\n",
    "    ax.loglog(nn, std_devs, \"o\", color=BLUE, ms=7, label=\"measured (2,000 repetitions)\")\n",
    "    ax.loglog(nn, sigma / np.sqrt(nn), color=ORANGE, lw=2, label=\"predicted: σ / √n\")\n",
    "    ax.set_xlabel(\"number of points n\")\n",
    "    ax.set_ylabel(\"standard deviation of the estimate\")\n",
    "    ax.set_title(f\"Measured slope: {slope:.3f}\")\n",
    "    ax.legend()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfeeb3d5",
   "metadata": {},
   "source": [
    "## 5. Proving that we are right: the confidence interval (20 min)\n",
    "\n",
    "For a mean of $N$ samples with variance $\\sigma^2$, the central limit theorem gives the asymptotic 95% confidence\n",
    "interval: estimate $\\pm 1.96\\, \\hat\\sigma / \\sqrt N$, where $\\hat\\sigma$ is the sample standard deviation\n",
    "of the draws.\n",
    "\n",
    "**5.1** Write `ci95(samples)`, which returns the pair (estimate, half-width) from the array of individual samples\n",
    "(for π, the samples are the values $4 \\times \\ind\\{x^2 + y^2 \\le 1\\}$)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af7f049c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def ci95(samples):\n",
    "    \"\"\"Mean and half-width of the asymptotic 95% confidence interval.\"\"\"\n",
    "    # TO COMPLETE\n",
    "    return None, None\n",
    "\n",
    "\n",
    "rng = np.random.default_rng(21)\n",
    "x, y = rng.random(1_000_000), rng.random(1_000_000)\n",
    "est, half = ci95(4.0 * (x * x + y * y <= 1))\n",
    "if ready(est, half):\n",
    "    print(f\"π ≈ {est:.4f} ± {half:.4f}   (is π = {math.pi:.4f} inside? {abs(est - math.pi) <= half})\")\n",
    "check(\"half-width with a million points\", half, 1.96 * sigma / 1000, 0.0002)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c0b9b7b",
   "metadata": {},
   "source": [
    "**5.2** Build 100 confidence intervals for π, each with $N = 1{,}000$ points, and draw them stacked: in blue those\n",
    "that contain π, in red those that miss it, and the vertical orange line $\\pi$.\n",
    "\n",
    "**Predict.** How many of the hundred intervals should miss π?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0b709a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(1812)\n",
    "# TO COMPLETE: centres[i], halves[i] = estimate and half-width of the i-th interval\n",
    "centres, halves = None, None\n",
    "\n",
    "if ready(centres, halves):\n",
    "    hit = np.abs(centres - math.pi) <= halves\n",
    "    fig, ax = plt.subplots(figsize=(6.5, 7))\n",
    "    for i in range(100):\n",
    "        colour = BLUE if hit[i] else RED\n",
    "        ax.plot([centres[i] - halves[i], centres[i] + halves[i]], [i, i], color=colour, lw=1.6)\n",
    "        ax.plot(centres[i], i, \"o\", color=colour, ms=2.5)\n",
    "    ax.axvline(math.pi, color=ORANGE, lw=2)\n",
    "    ax.set_yticks([])\n",
    "    ax.set_xlabel(\"95% confidence interval (N = 1,000 points)\")\n",
    "    ax.set_title(f\"{hit.sum()} intervals out of 100 catch π\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c75abf2d",
   "metadata": {},
   "source": [
    "**5.3** Measure the coverage rate over 2,000 intervals (still $N = 1{,}000$): the proportion of those that contain\n",
    "π. Is it compatible with 95%? (The standard deviation of a proportion estimated from 2,000 trials is about\n",
    "$\\sqrt{0.95 \\times 0.05 / 2000} \\approx 0.005$.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c11c20e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(7)\n",
    "# TO COMPLETE: coverage = proportion of the 2,000 intervals that contain π\n",
    "coverage = None\n",
    "check(\"coverage rate\", coverage, 0.95, 0.015)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bff22a33",
   "metadata": {},
   "source": [
    "**5.4 The answer to Ulam.** How many games of solitaire must be played to know the probability of success\n",
    "$p$ to within ± 1% (half-width of the 95% interval), whatever $p$? Hint: the variance of an indicator\n",
    "is $p(1-p) \\le 1/4$. Then check by simulation, with $p = 1/2$ (the worst case), that the half-width obtained\n",
    "is indeed about 0.01."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bf73d33",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TO COMPLETE: n_ulam = number of games needed (an integer)\n",
    "n_ulam = None\n",
    "check(\"games needed for ± 1%\", n_ulam, 9604, 0.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab33d940",
   "metadata": {},
   "source": [
    "## 6. Application: the price of a call option (15 min)\n",
    "\n",
    "A European call option with strike $K$ and maturity $T$ pays $(S_T - K)^+$. In the Black–Scholes model, under\n",
    "the “risk-neutral” probability,\n",
    "$S_T = S_0 \\exp\\big((r - \\sigma^2/2) T + \\sigma \\sqrt T\\, Z\\big)$ with $Z \\sim \\mathcal N(0, 1)$, and the price is\n",
    "$e^{-rT}\\, \\mathbb E[(S_T - K)^+]$. The judge is the Black–Scholes formula, given below.\n",
    "\n",
    "**6.1** Estimate the price with $N = 100{,}000$ samples for $S_0 = K = 100$, $r = 5\\%$, $\\sigma = 20\\%$, $T = 1$,\n",
    "give the 95% confidence interval and check that it contains the exact price."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bcf6f52",
   "metadata": {},
   "outputs": [],
   "source": [
    "def phi(x):\n",
    "    \"\"\"Cumulative distribution function of the standard normal distribution.\"\"\"\n",
    "    return 0.5 * (1 + math.erf(x / math.sqrt(2)))\n",
    "\n",
    "\n",
    "def bs_call(S0, K, r, sigma, T):\n",
    "    \"\"\"The judge: Black–Scholes price of a European call option.\"\"\"\n",
    "    d1 = (math.log(S0 / K) + (r + sigma**2 / 2) * T) / (sigma * math.sqrt(T))\n",
    "    return S0 * phi(d1) - K * math.exp(-r * T) * phi(d1 - sigma * math.sqrt(T))\n",
    "\n",
    "\n",
    "S0, K, r, sig, T = 100.0, 100.0, 0.05, 0.20, 1.0\n",
    "judge = bs_call(S0, K, r, sig, T)\n",
    "rng = np.random.default_rng(1973)\n",
    "# TO COMPLETE: payoffs = discounted payoffs e^{-rT} (S_T − K)^+ for 100,000 samples\n",
    "payoffs = None\n",
    "if ready(payoffs):\n",
    "    price, half = ci95(payoffs)\n",
    "    print(f\"Monte Carlo: {price:.3f} ± {half:.3f}   |   Black–Scholes: {judge:.4f}   |   inside: {abs(price - judge) <= half}\")\n",
    "    check(\"price of the call option\", price, judge, 0.15)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35859192",
   "metadata": {},
   "source": [
    "**6.2** How many samples would be needed for a half-width of one cent? Predict with $\\hat\\sigma$ (the standard\n",
    "deviation of the payoffs), then check with the number obtained."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f002be8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TO COMPLETE: n_cent = predicted number of samples for a half-width of €0.01\n",
    "n_cent = None\n",
    "check(\"samples for ± 1 cent\", n_cent, 8.4e6, 0.4e6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1621535",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Challenges (for those who have finished)\n",
    "\n",
    "### Challenge 1 — Buffon's needle, without cheating\n",
    "\n",
    "We drop a needle of length 1 on a plank floor whose cracks are 1 apart. It crosses a crack with\n",
    "probability $2/\\pi$ (Buffon, 1733 and 1777); Laplace (1812) suggests deducing π from it: $\\hat\\pi = 2n/k$ if $k$\n",
    "needles out of $n$ cross a crack.\n",
    "\n",
    "1. Simulate 3,000 needles (distance from the centre to the nearest crack uniform on $[0, 1/2]$, angle with the\n",
    "   cracks uniform) and estimate π. Draw the first 200: in blue those that cross a crack.\n",
    "2. **The trap.** Drawing a uniform angle on $[0, \\pi/2]$ assumes that you know π! Suggest a way of drawing a\n",
    "   uniform direction *without* using π (hint: a uniform point in the quarter disc, obtained by rejection).\n",
    "3. Why is $\\hat\\pi = 2n/k$ not unbiased, whereas $k/n$ is unbiased for $2/\\pi$?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e3ab60c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Challenge 1: your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a332bbce",
   "metadata": {},
   "source": [
    "### Challenge 2 — Is the dimension really invisible?\n",
    "\n",
    "The video claims that the error $\\sigma/\\sqrt N$ “does not see the dimension”. Estimate the volume of the unit ball\n",
    "of $\\mathbb R^d$ by drawing $N = 100{,}000$ uniform points in the cube $[-1, 1]^d$, for $d = 2, 4, \\dots, 14$.\n",
    "Compare with the exact volume $V_d = \\pi^{d/2} / \\Gamma(d/2 + 1)$ (`math.gamma`) and plot the **relative error**\n",
    "as a function of $d$. What happens, and what becomes of the video's promise?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2bf23824",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Challenge 2: your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d069a31",
   "metadata": {},
   "source": [
    "### Challenge 3 — When the interval lies\n",
    "\n",
    "A ruin that happens once in two hundred ($p = 0.005$). For $N = 100$, $1{,}000$ and $10{,}000$ simulations,\n",
    "measure over 2,000 repetitions the coverage rate of the interval “estimate ± 1.96 $\\hat\\sigma/\\sqrt N$”. What\n",
    "happens for $N = 100$? What is the interval when no ruin is observed?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7395dac1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Challenge 3: your turn"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
