Simple addition to random module - Student's t

Thomas Philips tkpmep at gmail.com
Wed Sep 2 15:51:15 CEST 2009


While the random module allows one to generate randome numbers with a
variety of distributions, some useful distributions are omitted - the
Student's t being among them. This distribution is easily derived from
the normal distribution and the chi-squared distribution (which in
turn is a special case of the gamma distribution). I edited and tested
a routine to generate random variables with a Student's t distribution
that I found on http://www.johndcook.com/python_student_t_rng.html,
which has  one bug - there is an extra factor of two in y. The
corrected and tested code follows - how does one go about getting this
incorporated into random so that the entire community can beneffit
from it?

Sincerely

Thomas Philips

def student_t(df):         # df is the number of degrees of freedom
    if df < 2  or int(df) != df:
       raise ValueError, 'student_tvariate: df must be a integer > 1'

    x = random.gauss(0, 1)
    y = random.gammavariate(df/2.0, 2)

    return x / (math.sqrt(y/df))


References:

1. Student's t distribution, including relationship to normal and chi-
squared distributions: http://en.wikipedia.org/wiki/Student's_t-distribution
2. Chi-squared distribution, including relationship to Gamma
distribution: http://en.wikipedia.org/wiki/Chi-square_distribution
3. John Cook's original version (with the extra factor of 2):
http://www.johndcook.com/python_student_t_rng.html



More information about the Python-list mailing list