Skip to content

Instantly share code, notes, and snippets.

@okomestudio
Created May 12, 2014 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okomestudio/67ede5ee10795c0bc018 to your computer and use it in GitHub Desktop.
Save okomestudio/67ede5ee10795c0bc018 to your computer and use it in GitHub Desktop.
Chi-squared distribution
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import chi2
def main():
colors = 'bgrcmyk'
n = 40000
for i, k in enumerate((1, 2, 3, 4, 6, 9)):
vs = []
for j in range(n):
v = (np.random.normal(size=k)**2).sum()
vs.append(v)
hs, es = np.histogram(vs, bins=2000, range=(0, 200), normed=True)
xs = (es[1:] + es[:-1]) / 2.
plt.plot(xs, hs, '.', color=colors[i])
rv = chi2(k)
plt.plot(xs, rv.pdf(xs), color=colors[i], label='k={}'.format(k))
plt.xlim(0, 8)
plt.ylim(0, 0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('pdf(x)')
plt.title('chi-squared distribution')
plt.show()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment