views:

341

answers:

3

What's the easiest way to generate random values according to a bimodal distribution in C or Python?

I could implement something like the Ziggurat algorithm or a Box-Muller transform, but if there's a ready-to-use library, or a simpler algorithm I don't know about, that'd be better.

+2  A: 

Aren't you just picking values either of two modal distributions?

http://docs.python.org/library/random.html#random.triangular

Sounds like you just toggle back and forth between two sets of parameters for your call to triangular.

def bimodal( low1, high1, mode1, low2, high2, mode2 ):
    toss = random.choice( (1, 2) )
    if toss == 1:
        return random.triangular( low1, high1, mode1 ) 
    else:
        return random.triangular( low2, high2, mode2 )

This may do everything you need.

S.Lott
Would that yield a true bimodal distribution? I don't think that'd work, that's why I asked the question in the first place.
Can Berk Güder
Worried about the overlapping region? Keep the two modes far enough apart -- and the slopes steep enough to reduce overlap. Box-Mueller will have a worse problem -- it's not bimodal. It's two independent values with the same mean and standard deviation.
S.Lott
unfortunately, I can't decide on the distribution (it's from a paper).
Can Berk Güder
it turns out this works better than I anticipated. thanks.
Can Berk Güder
+2  A: 

There's always the old-fashioned straight-forward accept-reject algorithm. If it was good enough for Johnny von Neumann it should be good enough for you ;-).

Charlie Martin
A: 

it should be rather trivial to do inverse transform sampling numerically using scipy.

Autoplectic