簡體   English   中英

在 numpy 中生成大小為 n、平均值 = 20、最小值 = 2 和最大值 = 25 的整數列表

[英]Generate list of integers with size n, mean = 20, min=2 and max=25 in numpy

我想生成一個大小為 n、平均值 = 20、最小值 = 2 和最大值 = 25 的整數列表。

並嘗試了下面的代碼。 這非常耗時。

# generate service time with mean = 20, min = 2 and max = 25
def gen_avg(n, expected_avg=20, a=2, b=25):
    while True:
        l = np.random.randint(a, b, size=n)
        avg = np.mean(l)

        if avg == expected_avg:
            return l

請幫我一些快速的方法

您可以生成一個隨機列表,然后通過替換大於平均值的數字(如果當前平均值太低)或替換小於平均值的數字(如果當前平均值太高)來稍微調整數字,就像這樣

def gen_avg(n, expected_avg=20, a=2, b=25):
    l = np.random.randint(a, b, size=n)
    while True:
        if np.mean(l) == expected_avg:
            break
        while np.mean(l) > expected_avg:
            c = np.random.choice(np.where(l>expected_avg)[0])
            l[c] = np.random.randint(a, expected_avg+1)
        while np.mean(l) < expected_avg:
            c = np.random.choice(np.where(l<expected_avg)[0])
            l[c] = np.random.randint(expected_avg, b)
        return l

這是假設您不關心從任何特別有趣的發行版中進行生產。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM