Simple addition to random module - Student's t

Thomas Philips tkpmep at
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,
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?


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))


1. Student's t distribution, including relationship to normal and chi-
squared distributions:'s_t-distribution
2. Chi-squared distribution, including relationship to Gamma
3. John Cook's original version (with the extra factor of 2):

More information about the Python-list mailing list