{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Gaussian Error Propagation with SymPy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Klaus Reygers, 2020" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "from sympy import *\n", "from IPython.display import display, Latex" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "def gaussian_error_propagation(f, vars):\n", " \"\"\"\n", " f: formula (sympy expression)\n", " vars: list of independent variables and corresponding uncertainties \n", " [(x1, sigma_x1), (x2, sigma_x2), ...]\n", " \"\"\"\n", " sum = S(0) # empty sympy expression\n", " for (x, sigma) in vars:\n", " sum += diff(f, x)**2 * sigma**2 \n", " return sqrt(simplify(sum))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Show usage for a simple example: Volume of a cylinder with radius $r$ and height $h$:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "r, h, sigma_r, sigma_h = symbols('r, h, sigma_r, sigma_h', positive=True)\n", "V = pi * r**2 * h # volume of a cylinder" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$V = \\pi h r^{2}, \\, \\sigma_V = \\pi r \\sqrt{4 h^{2} \\sigma_{r}^{2} + r^{2} \\sigma_{h}^{2}}$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "sigma_V = gaussian_error_propagation(V, [(r, sigma_r), (h, sigma_h)])\n", "display(Latex(f\"$V = {latex(V)}, \\, \\sigma_V = {latex(sigma_V)}$\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plug in some numbers and print the calculated volume with its uncertaity:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "r_meas = 3 # cm\n", "sigma_r_meas = 0.1 # cm\n", "h_meas = 5 # cm\n", "sigma_h_meas = 0.1 # cm" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$V = (141.4 \\pm 9.8) \\, \\mathrm{cm}^3$$" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "central_value = V.subs([(r,r_meas), (h, h_meas)]).evalf()\n", "sigma = sigma_V.subs([(r, r_meas), (sigma_r, sigma_r_meas), (h, h_meas), (sigma_h, sigma_h_meas)]).evalf()\n", "display(Latex(f\"$$V = ({central_value:0.1f} \\pm {sigma:.1f}) \\, \\mathrm{{cm}}^3$$\"))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.9.12" } }, "nbformat": 4, "nbformat_minor": 4 }