.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "api/gallery/combinatorics/inclusion_exclusion/plot_01_hat_check_problem.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_api_gallery_combinatorics_inclusion_exclusion_plot_01_hat_check_problem.py: The hat-check problem: derangements via inclusion-exclusion ================================================================== ``n`` people check their hats and receive one back at random; what's the probability nobody gets their own hat back? The answer converges to :math:`1/e` remarkably quickly. .. GENERATED FROM PYTHON SOURCE LINES 11-15 .. code-block:: Python import math from mathematicskit.combinatorics import derangement_count .. GENERATED FROM PYTHON SOURCE LINES 16-18 Probability of a total derangement, for increasing n ----------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 18-23 .. code-block:: Python for n in range(1, 11): d_n = derangement_count(n) probability = d_n / math.factorial(n) print(f"n={n:2d}: D_n={d_n:>10}, P(derangement) = {probability:.6f} (1/e = {1 / math.e:.6f})") .. rst-class:: sphx-glr-script-out .. code-block:: none n= 1: D_n= 0, P(derangement) = 0.000000 (1/e = 0.367879) n= 2: D_n= 1, P(derangement) = 0.500000 (1/e = 0.367879) n= 3: D_n= 2, P(derangement) = 0.333333 (1/e = 0.367879) n= 4: D_n= 9, P(derangement) = 0.375000 (1/e = 0.367879) n= 5: D_n= 44, P(derangement) = 0.366667 (1/e = 0.367879) n= 6: D_n= 265, P(derangement) = 0.368056 (1/e = 0.367879) n= 7: D_n= 1854, P(derangement) = 0.367857 (1/e = 0.367879) n= 8: D_n= 14833, P(derangement) = 0.367882 (1/e = 0.367879) n= 9: D_n= 133496, P(derangement) = 0.367879 (1/e = 0.367879) n=10: D_n= 1334961, P(derangement) = 0.367879 (1/e = 0.367879) .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.000 seconds) .. _sphx_glr_download_api_gallery_combinatorics_inclusion_exclusion_plot_01_hat_check_problem.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_01_hat_check_problem.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_01_hat_check_problem.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_01_hat_check_problem.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_