bhylu.com

Advertisements

NumPy Chi-square Distribution

A chi-square distribution has a positive degrees-of-freedom parameter and non-negative support. It appears in specific statistical constructions and tests.

How it works

One construction sums squares of independent standard normal variables; the count of those variables supplies degrees of freedom. Generating chi-square values does not itself perform a hypothesis test or compute a valid p-value for arbitrary data. A statistical test also needs assumptions, an appropriate statistic and a reference distribution justified for that statistic.

Run the code

Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.

For local work, use a separate virtual environment and run python chi-square.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.

Example

chi-square.py

import numpy as np

samples = np.random.default_rng(41).chisquare(df=3., size=50)
print(bool((samples >= 0).all()))
print(bool(np.isfinite(samples).all()))
try:
    np.random.default_rng(41).chisquare(df=0., size=2)
except ValueError:
    print("Rejected zero degrees of freedom")

Expected result

True
True
Rejected zero degrees of freedom

The valid draws stay in the non-negative domain, and the invalid parameter is rejected. The fixture teaches the generator’s contract while keeping statistical testing outside an unsupported shortcut.

Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.