Python函数根据所选分布绘制随机数

时间:2018-10-16 10:10:37

标签: python numpy matplotlib optional-parameters normal-distribution

我正在编写一个函数,该函数将从给定的分布(如泊松,正态或二项式)中抽取随机数。它使用一个参数作为样本数量,第二个参数作为分布类型。它会根据所选分布接受其他参数。因此,如果我采用正态样本,则其均值和标准差。

有没有写这个的最佳方法?

我的代码

import matplotlib.pyplot as plt
import numpy as np

def randNumberDistribution(samples, distribution,*optional):
    if distribution.capitalize() == 'Normal':
        if len(optional) == 2:
            mean, sd, = optional
            s = np.random.normal(mean, sd, samples)
            print(s)
            count, bins, ignored = plt.hist(s, 20, density=True)
            plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ),linewidth=3, color='y')
            plt.show()
        else:
            print("Invalid number of arguments")
    if distribution.capitalize() == 'Binomial':
        if len(optional) == 2:
            numOfTrials, probSuccess = optional # number of trials, probability of success(each trial)
            s = np.random.binomial(n, p, samples)
            count, bins, ignored = plt.hist(s, 14, density=True)
        else:
            print("Invalid number of arguments")
    if distribution.capitalize() == 'Poisson':
        if len(optional) == 1:
            exp = optional
            s = np.random.poisson(exp, samples) #Expectation of interval(should be >= 0)
            count, bins, ignored = plt.hist(s, 14, density=True)
        else:
            print("Invalid number of arguments")


print(randNumberDistribution(5,'Poisson',5))

1 个答案:

答案 0 :(得分:1)

您可以使用字典或类之类的东西,但是恕我直言,我发现您的代码简单易懂。只要满足条件,我将只使用elif来避免检查所有if语句。下面是一个简短的版本。您的else语句特定于给定的分发类型。我的只是检查了3种情况,并说对其他任何输入都无效。

def randNumberDistribution(samples, distribution,*optional):
    if distribution.capitalize() == 'Normal' and len(optional) == 2:
            mean, sd, = optional
            s = np.random.normal(mean, sd, samples)
            count, bins, ignored = plt.hist(s, 20, density=True)
            plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ),linewidth=3, color='y')
            plt.show()
    elif distribution.capitalize() == 'Binomial' and len(optional) == 2:
            n, p = optional # number of trials, probability of success(each trial)
            s = np.random.binomial(n, p, samples)
            count, bins, ignored = plt.hist(s, 14, density=True)
    elif distribution.capitalize() == 'Poisson' and len(optional) == 1:
            exp = optional
            s = np.random.poisson(exp, samples) #Expectation of interval(should be >= 0)
            count, bins, ignored = plt.hist(s, 14, density=True)
    else:
        print("Invalid number of arguments")