Search code examples
pythonrandomnormal-distribution

How can I generate n random values from a bimodal distribution in Python?


I tried generating and combining two unimodal distributions but think there's something wrong in my code.

N=400
mu, sigma = 100, 5
mu2, sigma2 = 10, 40
X1 = np.random.normal(mu, sigma, N)
X2 = np.random.normal(mu2, sigma2, N)
w = np.random.normal(0.5, 1, N)
X = w*X1 + (1-w)*X2
X = X.reshape(-1,2)

When I plot X I don't get a bimodal distribution


Solution

  • It's unclear where your problem is; it's also unclear what the purpose of the variable w is, and it's unclear how you judge you get an incorrect result, since we don't see the plot code, or any other code to confirm or reject a binomial distribution.
    That is, your example is too incomplete to exactly answer your question. But I can make an educated guess.

    If I do the following below:

    import numpy as np
    import matplotlib.pyplot as plt
    
    N=400
    mu, sigma = 100, 5
    mu2, sigma2 = 10, 40
    X1 = np.random.normal(mu, sigma, N)
    X2 = np.random.normal(mu2, sigma2, N)
    X = np.concatenate([X1, X2])
    plt.hist(X)
    

    and that yields the following figure:

    histogram of X