2022年8月21日 星期日

[python, signal, normal] How to generate a normal distribution data

How to generate a normal distribution data

井民全, Jing, mqjing@gmail.com


Example 1

Create a data array with 30 samples in which the properties of  mean is 80 and the standard deviation is 1.


Code

mean = 80

std = 1

N = 30

np.random.seed(1)

arrA= np.random.normal(mean, std, N)


Example 2

Create a 100 samples data array with mixed two distribution in which the first distribution has 30 samples with properties of means as 40 with standard deviation 1 and the second distribution has 70 samples with means as 60 and the standard deviation as 10.

Code

   

    np.random.seed(1)

    N = 100 # total samples


    # normal distribution list. mean = 40, std= 1, number of samples = 30%

    arrA = np.random.normal(40, 1, int(0.3 * N))    


     # normal distribution list. mean = 60, std= 10, number of samples = 70%

    arrB = np.random.normal(60, scale=10, size=int(0.7 * N)) 

    X = np.concatenate((arrA, arrB))

   

    fig, axes = plt.subplots(nrows=2, sharex=True, gridspec_kw={"height_ratios": [1,1]})

    fig.suptitle('Fig. Test of Normal Distribution and K-means.')

    fig.canvas.set_window_title('Test of Normal Distribution')

    

    # show all samples

    i = 0

    axes[i].plot([x for x in range(0, X.size)], X, "tab:red", label="X")

    axes[i].set_title("(a) Data X with two distributions.")

    axes[i].set_ylabel("Value")

    axes[i].set_xlabel("Samples")

    axes[i].grid()

    axes[i].legend()

    


    # show histogram

    i = 1

    bins = np.linspace(0, N, N)

    axes[i].hist(X, bins=bins, fc='#AAAAFF')

    axes[i].set_title("(b) Show the frequency histogram of X.")

    axes[i].set_ylabel("Histogram")

    axes[i].set_xlabel("Values")

    

    plt.tight_layout() # Prvent the figure title overlaps axes label

    plt.show()




Result



Reference

  1. https://numpy.org/doc/stable/reference/random/generated/numpy.random.normal.html