momentchi2

raw JSON →
0.1.8 verified Mon Apr 27 auth: no python

A Python library for computing the cumulative distribution function (CDF) of a weighted sum of chi-squared random variables. Version 0.1.8 supports Imhof's method, Davies' method, and moment-based approximations. Developed by the PyPA, with monthly or less frequent releases.

pip install momentchi2
error ValueError: The weights and degrees of freedom must have the same length
cause Mismatched lengths of weights and df arrays.
fix
Check that len(weights) == len(df) and adjust accordingly.
error ImportError: No module named 'momentchi2'
cause The library is not installed or the package name is misspelled.
fix
Run pip install momentchi2 and ensure the correct Python environment is used.
gotcha The library function names differ from the original R package 'momentchi2'. Ensure you use Python function names: imhof, davies, moment_approximation, etc.
fix Use import momentchi2 and call momentchi2.imhof(...) etc.
deprecated The 'davies' method may be deprecated in future versions due to numerical stability issues. Prefer 'imhof' for reliable results.
fix Use momentchi2.imhof() instead of momentchi2.davies().
gotcha Weights and degrees of freedom vectors must be of equal length, otherwise an unhelpful ValueError is raised.
fix Ensure len(weights) == len(df). If df is a scalar, repeat it to match the number of weights.

Compute the CDF of a weighted sum of chi-squared random variables using Imhof's method. For other methods (e.g., Davies, moment-based), replace imhof with davies or moment_approximation.

import momentchi2

# Example: CDF of a weighted sum of chi-squared variables
# weights and degrees of freedom
df = [1, 2, 1]
weights = [0.5, 0.3, 0.2]
q = 1.5

# Use Imhof's method
p = momentchi2.imhof(q, weights, df)
print(f"CDF value: {p:.6f}")