Student-t random number generator

The following code will generate samples from a Student-t distribution with ν (nu) degrees of freedom.

import math 
import random

# nu equals number of degrees of freedom
def student_t(nu): 
    x = random.gauss(0.0, 1.0)
    y = 2.0*random.gammavariate(0.5*nu, 2.0)
    return x / (math.sqrt(y/nu))

This code is in the public domain. Do whatever you want to with it, no strings attached.

See also:
Stand-alone numerical code
Python random number generation



John D. Cook photo


Need help making sense of data?