{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Cosmology and the Big Bang\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/cosmology-and-big-bang). This notebook includes the lesson text and its Python examples in reading order. Run the setup cell, then run the remaining cells from top to bottom. In Colab, use File → Save a copy in Drive to keep your edits. You can run and edit this view without changing the course source. Examples use illustrative data unless stated otherwise."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-001",
      "metadata": {},
      "source": [
        "import importlib.metadata\n",
        "import subprocess\n",
        "import sys\n",
        "\n",
        "requirements = {\"numpy\": (2, 0), \"sympy\": (1, 13), \"matplotlib\": (3, 8)}\n",
        "to_install = []\n",
        "for package, minimum in requirements.items():\n",
        "    try:\n",
        "        installed = importlib.metadata.version(package)\n",
        "        version = tuple(int(part) for part in installed.split(\".\")[:2])\n",
        "    except importlib.metadata.PackageNotFoundError:\n",
        "        version = (0, 0)\n",
        "    if version < minimum:\n",
        "        to_install.append(f\"{package}>={minimum[0]}.{minimum[1]}\")\n",
        "if to_install:\n",
        "    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", *to_install])\n",
        "\n",
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "print(\"Python\", sys.version.split()[0])\n",
        "print(\"NumPy\", np.__version__)\n",
        "print(\"SymPy\", sp.__version__)\n",
        "print(\"Matplotlib\", matplotlib.__version__)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-002",
      "metadata": {},
      "source": [
        "Cosmology studies the universe on its largest scales. It connects observations of\n",
        "galaxies, light, and matter with a mathematical description of how space changes\n",
        "with time. The standard Big Bang model says that the observable universe evolved\n",
        "from an earlier state that was much hotter and denser than it is now. It does\n",
        "**not** describe matter exploding from one special point into pre-existing empty\n",
        "space. In the model, space itself expands, and no ordinary location is selected as\n",
        "the centre of that expansion.\n",
        "\n",
        "This distinction matters. An observer in almost any unbound galaxy sees distant\n",
        "galaxies recede on average. That observation does not put the observer at the\n",
        "centre, just as every dot on the surface of an inflating balloon sees other dots\n",
        "move away. The balloon is only an analogy: its two-dimensional surface stands for\n",
        "three-dimensional space, and its surrounding room is not part of the cosmological\n",
        "model.\n",
        "\n",
        "## The scale factor describes expansion\n",
        "\n",
        "Cosmologists represent the changing size of large-scale spatial separations with\n",
        "the scale factor $a(t)$.\n",
        "It is conventional to set its present value to\n",
        "$a(t_0)=1$.\n",
        "If two galaxies simply follow the large-scale expansion, their proper separation\n",
        "at a chosen cosmic time is proportional to $a(t)$.\n",
        "Local systems such as atoms, people, planets, and gravitationally bound galaxies\n",
        "do not expand with this rule: electromagnetic and gravitational binding dominates\n",
        "on those scales.\n",
        "\n",
        "Expansion stretches freely travelling light. If a photon was emitted when the\n",
        "scale factor was $a_{\\mathrm{em}}$\n",
        "and observed today, its cosmological redshift is\n",
        "\n",
        "\n",
        "$$\n",
        "1+z=\\frac{\\lambda_{\\mathrm{obs}}}{\\lambda_{\\mathrm{em}}}=\\frac{a(t_0)}{a(t_{\\mathrm{em}})}\n",
        "$$\n",
        "\n",
        "\n",
        "Here $z$ is dimensionless. A positive\n",
        "value means the observed wavelength is longer than the emitted wavelength. At\n",
        "cosmological distances, this scale-factor interpretation is more useful than\n",
        "treating the entire shift as an ordinary Doppler effect through static space."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "rest_wavelength_nm, observed_wavelength_nm = 656.3, 984.45\n",
        "redshift = observed_wavelength_nm / rest_wavelength_nm - 1\n",
        "emission_scale_factor = 1 / (1 + redshift)\n",
        "print(\"Illustrative line redshift:\", redshift)\n",
        "print(\"Emission scale factor with a_today=1:\", emission_scale_factor)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "The spectral line must be identified correctly, and the instrument calibration\n",
        "and measurement uncertainty must be retained. The final line also assumes the\n",
        "present-day normalization $a(t_0)=1$.\n",
        "\n",
        "## The Hubble–Lemaître relation\n",
        "\n",
        "The fractional expansion rate is the Hubble parameter,\n",
        "\n",
        "\n",
        "$$\n",
        "H(t)=\\frac{\\dot a(t)}{a(t)}\n",
        "$$\n",
        "\n",
        "\n",
        "where the dot means a derivative with respect to cosmic time. For a nearby galaxy\n",
        "that follows the smooth expansion, the recession speed is approximately\n",
        "\n",
        "\n",
        "$$\n",
        "v\\approx H_0d\n",
        "$$\n",
        "\n",
        "\n",
        "where $H_0$ is the present\n",
        "value of the Hubble parameter and $d$\n",
        "is an appropriate nearby distance. This is a low-redshift approximation. At large\n",
        "redshift, recession speed and distance are not uniquely defined without specifying\n",
        "a cosmological model and a distance convention.\n",
        "\n",
        "The units provide a quick check. If $H_0$\n",
        "is expressed as speed per distance, multiplying it by distance gives speed.\n",
        "Doubling $d$\n",
        "therefore doubles the predicted local recession speed. The linear relation does\n",
        "not imply that every galaxy has only this motion: galaxies also have local or\n",
        "peculiar velocities caused by nearby gravitational fields.\n",
        "\n",
        "## The Friedmann equation\n",
        "\n",
        "General relativity relates expansion to the contents and spatial geometry of the\n",
        "universe. For a homogeneous and isotropic model, one central equation is\n",
        "\n",
        "\n",
        "$$\n",
        "H^2=\\left(\\frac{\\dot a}{a}\\right)^2=\\frac{8\\pi G}{3}\\rho-\\frac{kc^2}{a^2}+\\frac{\\Lambda c^2}{3}\n",
        "$$\n",
        "\n",
        "\n",
        "The density $\\rho$\n",
        "includes the relevant forms of mass-energy. The constant\n",
        "$G$ is Newton's gravitational\n",
        "constant, $c$ is the speed of light,\n",
        "$k$ represents spatial\n",
        "curvature, and $\\Lambda$ is the\n",
        "cosmological constant. The equation does not predict a unique history until the\n",
        "components, their evolution, and initial or measured parameters are supplied.\n",
        "\n",
        "Read the equation as an accounting rule rather than as a wall of symbols:"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "# Illustrative flat matter + cosmological-constant model, not a data fit.\n",
        "H0_km_s_mpc, omega_m, omega_lambda = 70.0, 0.3, 0.7\n",
        "H0_per_s = H0_km_s_mpc * 1000 / 3.085677581e22\n",
        "\n",
        "\n",
        "def hubble(z):\n",
        "    return H0_per_s * np.sqrt(omega_m * (1 + z) ** 3 + omega_lambda)\n",
        "\n",
        "\n",
        "print(\"Hubble rate at z=0.5 (1/s):\", hubble(0.5))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "This Python exposes the sign of the curvature term and prevents silently\n",
        "taking the square root of a negative result. In practical calculations, each\n",
        "energy component has its own density evolution. Nonrelativistic matter dilutes\n",
        "approximately as $a^{-3}$\n",
        "because volume grows as $a^3$.\n",
        "Radiation dilutes approximately as $a^{-4}$:\n",
        "three powers come from volume and one more from wavelength stretching.\n",
        "\n",
        "Density parameters compare each contribution with a critical density. With a\n",
        "consistent sign convention they can be summarized at a chosen epoch by\n",
        "\n",
        "\n",
        "$$\n",
        "\\Omega_{\\mathrm{m}}+\\Omega_{\\mathrm{r}}+\\Omega_{\\Lambda}+\\Omega_{\\mathrm{k}}=1\n",
        "$$\n",
        "\n",
        "\n",
        "The subscripts denote matter, radiation, cosmological-constant-like dark energy,\n",
        "and curvature. Numerical values inferred from observations depend on the chosen\n",
        "model, datasets, calibrations, and analysis assumptions; they should not be\n",
        "treated as source-free constants.\n",
        "\n",
        "## A thermal history, not a single instant\n",
        "\n",
        "Running the expansion model backward leads to hotter, denser conditions. The name\n",
        "“Big Bang” refers to this evolving early state, not to a conventional explosion.\n",
        "The well-tested hot Big Bang account covers a sequence of physical eras:\n",
        "\n",
        "1. At very early high temperatures, particles and radiation interacted rapidly.\n",
        "   Present observations do not directly establish what occurred at an initial\n",
        "   mathematical singularity, where classical general relativity is expected to be\n",
        "   incomplete.\n",
        "2. As expansion lowered the temperature, protons and neutrons participated in\n",
        "   reactions that produced mostly hydrogen and helium nuclei, with small amounts\n",
        "   of other light nuclei. This is Big Bang nucleosynthesis.\n",
        "3. Much later, the temperature became low enough for electrons to bind to nuclei.\n",
        "   Photons then travelled far more freely. Those photons are observed today as the\n",
        "   cosmic microwave background, cooled by cosmic expansion.\n",
        "4. Small density differences grew under gravity. Matter collected into the\n",
        "   structures that became galaxies, clusters, and the large-scale cosmic web.\n",
        "\n",
        "These stages join nuclear physics, atomic physics, thermodynamics, gravity, and\n",
        "observational astronomy. Their times and temperatures are model-dependent, so a\n",
        "timeline should label its assumptions rather than display unjustified precision.\n",
        "\n",
        "## Independent lines of evidence\n",
        "\n",
        "The expanding hot-universe model is supported by several observations that test\n",
        "different parts of the account. Galaxy redshifts and distance indicators reveal\n",
        "the large-scale expansion. The cosmic microwave background has an extremely\n",
        "thermal spectrum and small directional variations that preserve information about\n",
        "the early universe. Measured abundances of light elements test nuclear reactions\n",
        "in a hot early phase. The distribution and evolution of large-scale structure test\n",
        "how density variations grew.\n",
        "\n",
        "No single item should be presented as the whole case. Agreement across independent\n",
        "measurements is powerful because changing a model to fit one dataset may spoil its\n",
        "fit to another. Conversely, disagreement can point to underestimated systematic\n",
        "error, incorrect parameter assumptions, or missing physics.\n",
        "\n",
        "Dark matter is introduced because luminous matter alone does not explain several\n",
        "gravitational observations and the observed growth of structure. Dark energy is\n",
        "the name for the component or modification used to account for accelerated cosmic\n",
        "expansion. These labels describe inferred roles; the simple cosmological model does\n",
        "not by itself identify the microscopic nature of either one.\n",
        "\n",
        "## Distance and time require definitions\n",
        "\n",
        "In an expanding universe, “the distance to a galaxy” can mean several different\n",
        "quantities. Proper distance compares positions at a selected cosmic time. Comoving\n",
        "distance factors out expansion and assigns expansion-following galaxies fixed\n",
        "coordinates. Luminosity distance is defined through observed brightness, while\n",
        "angular-diameter distance connects physical size with apparent angle. These\n",
        "distances agree approximately for nearby objects but differ at large redshift.\n",
        "\n",
        "Lookback time is how long the observed light has travelled according to the model.\n",
        "It can be computed from\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{dt}{dz}=-\\frac{1}{(1+z)H(z)}\n",
        "$$\n",
        "\n",
        "\n",
        "The minus sign says that larger redshift corresponds to earlier cosmic time. A\n",
        "numerical integral can accumulate positive lookback time in small redshift steps:"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "z = np.linspace(0, 0.5, 10001)\n",
        "lookback_seconds = np.trapezoid(1 / ((1 + z) * hubble(z)), z)\n",
        "seconds_per_gigayear = 1e9 * 365.25 * 24 * 3600\n",
        "print(f\"Model lookback time: {lookback_seconds/seconds_per_gigayear:.3f} billion years\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "The calculation should be repeated with smaller steps. If the answer changes\n",
        "materially, the original discretization was too coarse. Model uncertainty and\n",
        "parameter uncertainty are separate from numerical integration error and should be\n",
        "reported separately.\n",
        "\n",
        "## Horizons, inflation, and limits of the account\n",
        "\n",
        "Because light has a finite speed and the universe has a finite expansion history,\n",
        "we can observe only a limited region. The observable universe is therefore not\n",
        "necessarily the whole universe. A horizon is a limit on causal contact or\n",
        "observation under a specified cosmological history; it is not a physical wall.\n",
        "Very distant galaxies can have recession rates greater than\n",
        "$c$\n",
        "without locally moving through space faster than light. Special relativity still\n",
        "limits the speed measured between nearby observers; cosmological recession over a\n",
        "changing geometry is a different comparison.\n",
        "\n",
        "Inflation is a proposed period of very rapid early expansion that helps explain\n",
        "features such as large-scale uniformity and the origin of primordial fluctuations.\n",
        "Its broad observational consequences are studied seriously, but the underlying\n",
        "mechanism and detailed model are not settled by the elementary Big Bang account.\n",
        "Likewise, extrapolating the Friedmann equation to a classical singularity signals\n",
        "the limit of the theory rather than a complete physical description of an\n",
        "absolute beginning.\n",
        "\n",
        "A careful cosmological conclusion therefore includes scope. State the assumed\n",
        "geometry and contents, define the distance and time quantities, preserve parameter\n",
        "uncertainties, and distinguish observed evidence from theoretical extrapolation.\n",
        "The equations provide a coherent history of an expanding, cooling universe; they\n",
        "do not remove the need to test each part of that history against independent data.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Inspect an illustrative flat matter-plus-cosmological-constant expansion model. The question for this calculation is precise: how does **expansion rate divided by H0**\n",
        "change when we change **redshift**, while keeping the other choices fixed?\n",
        "The earlier sections explain the physical relationship. Here we turn one part of that\n",
        "relationship into a calculation that you can run, inspect, and change in Google Colab.\n",
        "\n",
        "The density fractions are chosen example parameters and radiation is neglected over this redshift range. Keep that sentence beside the results. A formula can return a number outside\n",
        "its useful range, and a plotting library will usually draw that number without asking\n",
        "whether the physical assumptions still hold. The selected interval is from\n",
        "0 to 3 dimensionless. It gives us a specific domain to discuss\n",
        "instead of leaving the graph's range to a software default.\n",
        "\n",
        "Use the notebook link above the lesson, run the setup cell, and then run the cells in\n",
        "order. The code below is also included there. NumPy handles the arrays of numerical\n",
        "values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these\n",
        "libraries or notebook cells are unfamiliar, start with\n",
        "[Your first physics notebook](https://tirta.co/a-byte-of-physics/your-first-physics-notebook).\n",
        "\n",
        "### State the relationship before choosing a graph\n",
        "\n",
        "In this small example, `q` stands for redshift, expressed in dimensionless. The output is\n",
        "expansion rate divided by H0, expressed in dimensionless. The equation below uses the numerical values in those\n",
        "units. Any fixed coefficients therefore carry the units needed to make the relation\n",
        "consistent. A value supplied in another unit must be converted before it enters this\n",
        "expression.\n",
        "\n",
        "\n",
        "$$\n",
        "f(q) = \\sqrt{0.3 \\left(q + 1\\right)^{3} + 0.7}\n",
        "$$\n",
        "\n",
        "\n",
        "This is a function of one changing input. It is not a statement that the physical\n",
        "system has only one variable. We deliberately hold the other inputs fixed so that one\n",
        "cause of variation is visible. Changing several inputs at once would make it harder\n",
        "to tell which change produced the output difference. Write down the held-fixed choices\n",
        "before trying a different experiment.\n",
        "\n",
        "At 0.5 dimensionless, the expression gives 1.30863 dimensionless. This is our\n",
        "reference calculation. It is a prediction of the stated example, not a new measurement.\n",
        "Its displayed digits help us compare implementations. They should not be read as a\n",
        "claim that physical inputs are known to six significant figures."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-009",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "q = sp.Symbol(\"q\", real=True)\n",
        "expression = sp.sympify(\"sqrt(0.3*(1+q)**3+0.7)\", locals={\"q\": q})\n",
        "reference_input = 0.5\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"dimensionless\")\n",
        "print(\"Predicted expansion rate divided by H0:\", reference_output, \"dimensionless\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-010",
      "metadata": {},
      "source": [
        "`sp.Symbol` declares a mathematical symbol. It does not assign a numerical measurement\n",
        "to that symbol. `subs` then replaces the symbol with our chosen input, and `float`\n",
        "converts the resulting symbolic number into a standard Python numerical value.\n",
        "Keeping these steps separate lets us inspect the equation before numerical substitution.\n",
        "It also prevents a later plot from becoming the only surviving record of the model.\n",
        "\n",
        "### Compare a few cases you can explain\n",
        "\n",
        "Before drawing hundreds of points, calculate three. The lower endpoint gives\n",
        "1 dimensionless. The midpoint, at 1.5 dimensionless, gives\n",
        "2.3211 dimensionless. The upper endpoint gives 4.46094 dimensionless.\n",
        "Read these together with the assumptions: they describe different choices of redshift\n",
        "within the same example, with the other inputs held fixed.\n",
        "\n",
        "These three values are a useful first check, but they do not establish the shape between\n",
        "them. Two endpoints can be equal even when the curve bends or oscillates in between.\n",
        "Likewise, a large change between endpoints does not tell us whether the relationship is\n",
        "linear. We need the equation and intermediate samples to answer those questions."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-011",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([0.0, 1.5, 3.0])\n",
        "outputs = np.asarray(evaluate(inputs), dtype=float)\n",
        "outputs = np.broadcast_to(outputs, inputs.shape)\n",
        "for input_value, output_value in zip(inputs, outputs):\n",
        "    print(f\"{input_value:.6g} dimensionless -> {output_value:.6g} dimensionless\")\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-012",
      "metadata": {},
      "source": [
        "`lambdify` turns the symbolic expression into a numerical function. We explicitly select\n",
        "NumPy as its numerical backend so it can accept an array. The same expression now has\n",
        "two useful forms: one for algebra and one for calculating many cases. The assertion\n",
        "checks that the chosen inputs produce finite outputs. It would catch an infinity or an\n",
        "undefined numerical result, but a finite value can still be physically inappropriate.\n",
        "\n",
        "### Make a graph that answers the question\n",
        "\n",
        "The horizontal axis shows redshift; the vertical axis shows expansion rate divided by H0. Every plotted\n",
        "point is a prediction of the same expression. We mark the reference case separately\n",
        "so that a reader can connect the earlier printed value to its place on the curve.\n",
        "The axis labels include units because a shape without a scale cannot tell us the size\n",
        "of a physical effect."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-013",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(0.0, 3.0, 301)\n",
        "output_grid = np.asarray(evaluate(input_grid), dtype=float)\n",
        "output_grid = np.broadcast_to(output_grid, input_grid.shape)\n",
        "fig, ax = plt.subplots(figsize=(7, 4))\n",
        "ax.plot(input_grid, output_grid, label=\"Stated model\")\n",
        "ax.scatter([reference_input], [reference_output], label=\"Reference case\", zorder=3)\n",
        "ax.set_xlabel(\"Redshift (dimensionless)\")\n",
        "ax.set_ylabel(\"Expansion rate divided by h0 (dimensionless)\")\n",
        "ax.legend()\n",
        "ax.grid(alpha=0.25)\n",
        "fig.tight_layout()\n",
        "plt.show()\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-014",
      "metadata": {},
      "source": [
        "Look for a sign change, a turning point, or a region where the curve becomes steep.\n",
        "Connect each feature to the expression rather than to the colour of the line. If the\n",
        "curve has a minimum or maximum, changing the input in opposite directions may have\n",
        "similar effects on the output near that point. If it is nearly straight over a short\n",
        "interval, a local linear approximation may be useful even when the complete expression\n",
        "is nonlinear.\n",
        "\n",
        "Increasing the number of samples makes the line smoother and may reveal features that\n",
        "a coarse grid missed. It does not improve the physical inputs or enlarge the model's\n",
        "validity range. For quantities that can take only discrete values, use the line as a\n",
        "guide to the relationship and interpret only the allowed input values. A plotting\n",
        "function does not enforce such restrictions for you.\n",
        "\n",
        "### Measure the local sensitivity\n",
        "\n",
        "A derivative asks a more specific question than the whole graph: how quickly does\n",
        "expansion rate divided by H0 change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 0.5 dimensionless is\n",
        "0.773713 in those ratio units. Locally, the output increases as the\n",
        "input increases. This statement is local; the sign or size of the slope can be different\n",
        "elsewhere on the curve.\n",
        "\n",
        "\n",
        "$$\n",
        "f'(q) = \\frac{0.45 \\left(q + 1\\right)^{2}}{\\sqrt{0.3 \\left(q + 1\\right)^{3} + 0.7}}\n",
        "$$\n",
        "\n",
        "\n",
        "For a small input change, multiply the derivative by that change to estimate the output\n",
        "change. Then compare that estimate with a fresh evaluation of the full expression.\n",
        "The distinction between these two calculations matters: the derivative gives a tangent\n",
        "approximation, while substitution evaluates the chosen expression at the new point."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-015",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 0.515\n",
        "linear_prediction = reference_output + slope_at_reference * (\n",
        "    changed_input - reference_input\n",
        ")\n",
        "full_prediction = float(evaluate(changed_input))\n",
        "print(\"Symbolic derivative:\", slope_expression)\n",
        "print(\"Tangent prediction:\", linear_prediction, \"dimensionless\")\n",
        "print(\"Full expression:\", full_prediction, \"dimensionless\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"dimensionless\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-016",
      "metadata": {},
      "source": [
        "Here the changed input is 0.515 dimensionless. The tangent estimate is\n",
        "1.32023 dimensionless, while the full expression gives\n",
        "1.3203 dimensionless. If the two values are close, it means the chosen\n",
        "input change is small enough for this local approximation at this point. It does not\n",
        "mean the entire model is linear. If the slope is zero, a quadratic or higher-order term\n",
        "may supply the leading change instead.\n",
        "\n",
        "This is also the beginning of uncertainty propagation. If the input has a small stated\n",
        "standard uncertainty, the magnitude of the slope times that uncertainty estimates one\n",
        "contribution to output uncertainty. Do not automatically use the same rule for a wide\n",
        "interval, a discontinuity, a turning point with zero first derivative, or several\n",
        "correlated uncertain inputs. Those situations need more of the model than one slope.\n",
        "\n",
        "### Check the derivative with numerical differences\n",
        "\n",
        "We can estimate the same slope from values on either side of the reference point.\n",
        "Subtract the lower output from the upper output and divide by twice the input step.\n",
        "Parentheses are essential: the entire output difference must be divided by the entire\n",
        "input interval. Without them, Python can execute a different mathematical expression\n",
        "while still producing a plausible number.\n",
        "\n",
        "The calculation below uses three decreasing step sizes. Each estimate is compared with\n",
        "the symbolic derivative, so the reference is independent of the numerical difference\n",
        "formula. Near an endpoint, it is acceptable here to evaluate a small extension only\n",
        "because the displayed mathematical expression is smooth there; such a check does not\n",
        "assert that extrapolated values describe additional physical cases."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-017",
      "metadata": {},
      "source": [
        "input_span = 3.0\n",
        "for fraction in [1e-2, 1e-3, 1e-4]:\n",
        "    step = input_span * fraction\n",
        "    upper = float(evaluate(reference_input + step))\n",
        "    lower = float(evaluate(reference_input - step))\n",
        "    numerical_slope = (upper - lower) / (2 * step)\n",
        "    difference = numerical_slope - slope_at_reference\n",
        "    print(f\"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-018",
      "metadata": {},
      "source": [
        "For a smooth function, reducing the step often reduces the approximation error at first.\n",
        "Very small steps can eventually make subtraction of nearly equal floating-point values\n",
        "less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare\n",
        "the observed behaviour over a useful range of steps instead of choosing the smallest\n",
        "number the computer can represent.\n",
        "\n",
        "An absolute slope difference is useful when the expected slope is near zero. A relative\n",
        "difference would divide by a very small reference and could look enormous even when the\n",
        "absolute discrepancy is tiny. Away from zero, a relative difference can help compare\n",
        "quantities with very different scales. The tolerance should reflect the question and\n",
        "the numerical method, rather than a universal decimal threshold copied into every test.\n",
        "\n",
        "### Change the example and preserve the reasoning\n",
        "\n",
        "Make one copy of the reference calculation before editing it. Choose a second value of\n",
        "redshift inside the stated interval, predict whether expansion rate divided by H0 will rise or fall,\n",
        "and then evaluate the expression. Place the prediction and the result in a text cell.\n",
        "If they disagree, identify whether the mistake was in the sign, the unit conversion,\n",
        "the algebra, or the assumption about how the curve behaves.\n",
        "\n",
        "Next choose a shorter plotting interval around the reference point. Compare the local\n",
        "curve with its tangent approximation. Then widen the interval again. The difference\n",
        "shows why a useful local estimate need not describe the whole range. Keep the axis\n",
        "labels and numerical scale visible when comparing the plots; automatic axis limits can\n",
        "make two different effects appear equally large.\n",
        "\n",
        "Finally, return to the physical limit stated at the start: The density fractions are chosen example parameters and radiation is neglected over this redshift range. Describe one change\n",
        "to the setup that would violate that limit. State what new input, equation, or observation\n",
        "would be needed before trusting an answer in the changed situation. This last step\n",
        "connects the Python experiment to the physics instead of treating successful execution\n",
        "as the only criterion for a useful result.\n",
        "\n",
        "Before saving, restart the runtime and run all cells in order. A result that depends on\n",
        "an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep\n",
        "unrounded values for later calculations, round only the reported output, and label any\n",
        "new data as measured, assumed, or generated. The graph and printed values should remain\n",
        "traceable to the same expression and the same choices of inputs.\n",
        "\n",
        "### Recover the output change by integrating the slope\n",
        "\n",
        "There is another way to check that the expression and its derivative describe the same\n",
        "relationship. Add up the small output changes predicted by the slope across the chosen\n",
        "input interval. In the continuous limit, this integral equals the output at the upper\n",
        "endpoint minus the output at the lower endpoint. The result has units of dimensionless:\n",
        "the input unit in the integration cancels the input unit in the denominator of the slope.\n",
        "\n",
        "This statement is about the mathematics of this particular relationship. It does not\n",
        "assign a new physical meaning to an arbitrary area under a graph. For example, an area\n",
        "under force versus distance represents work, while an area under a different pair of\n",
        "quantities may represent something else or have no standard name. Always carry the\n",
        "axis units through the calculation before naming an integral."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-019",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(3.0) - evaluate(0.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.0, 3.0, points)\n",
        "    slopes = np.asarray(slope_function(grid), dtype=float)\n",
        "    slopes = np.broadcast_to(slopes, grid.shape)\n",
        "    integrated_change = np.trapezoid(slopes, grid)\n",
        "    print(\n",
        "        points,\n",
        "        \"integrated change:\",\n",
        "        integrated_change,\n",
        "        \"endpoint change:\",\n",
        "        endpoint_change,\n",
        "    )\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-020",
      "metadata": {},
      "source": [
        "The trapezoidal rule joins neighbouring slope samples with straight segments and adds\n",
        "their signed areas. A negative contribution remains negative; replacing every slope\n",
        "by its magnitude would calculate a different quantity. Increasing the sample count\n",
        "provides a practical refinement check. If the values do not settle toward the endpoint\n",
        "difference, first inspect the interval, singularities, and array ordering.\n",
        "\n",
        "Do not conclude that two agreeing calculations prove the model is physically complete.\n",
        "Both use the same selected relationship, so an omitted effect would be omitted from\n",
        "both. Their agreement is evidence that the numerical tools implement that relationship\n",
        "consistently. Comparing with an independent experiment or a more appropriate physical\n",
        "model is a separate test.\n",
        "\n",
        "Keep this comparison in the notebook when you change the expression. It is particularly\n",
        "useful after adding a coefficient, changing a sign convention, or converting an input\n",
        "unit. A code cell that produces a smooth graph can conceal these mistakes; a second\n",
        "calculation of the same output change gives you another place to notice them.\n",
        "\n",
        "## Sources\n",
        "\n",
        "- [OpenStax, *University Physics Volume 3*, Section 11.6: The Big Bang](https://openstax.org/books/university-physics-volume-3/pages/11-6-the-big-bang).\n",
        "- [OpenStax, *University Physics Volume 3*, Section 11.7: Evolution of the Early Universe](https://openstax.org/books/university-physics-volume-3/pages/11-7-evolution-of-the-early-universe).\n",
        "- [Physics LibreTexts, Astronomy and Cosmology](https://phys.libretexts.org/Bookshelves/Astronomy__Cosmology).\n",
        "- [Tipler and Llewellyn, *Modern Physics* (PDF)](https://web.pdx.edu/~pmoeck/books/Tipler_Llewellyn.pdf).\n",
        "- Benjamin Crowell, *Light and Matter*, locally archived course reference."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "cosmology-and-big-bang.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/cosmology-and-big-bang",
      "source_sha256": "6204319066b2504df2f1607b2c3533f6ee999735b311d7596001ed9381e075a8"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
