87. 随机数生成器


rand() 用于生成 0 到 1 之间的随机数。它从不返回 0 或 1,始终返回 0 到 1 之间的值。数字在一次 awk 运行中是随机的,但在运行之间是可预测的。

awk 使用一种算法来生成随机数,并且由于该算法是固定的,因此数字是可重复的。

以下示例生成 0 到 100 之间的 1000 个随机数,并显示每个数字的生成频率。

$ cat rand.awk
BEGIN {
    while(i<1000)
    {
        n = int(rand()*100);
        rnd[n]++;
        i++;
    }
    for(i=0;i<=100;i++) {
        print i,"Occured", rnd[i], "times";
    }
}

$ awk -f rand.awk
0 Occured 6 times
1 Occured 16 times
2 Occured 12 times
3 Occured 6 times
4 Occured 13 times
5 Occured 13 times
6 Occured 8 times
7 Occured 7 times
8 Occured 16 times
9 Occured 9 times
10 Occured 6 times
11 Occured 9 times
12 Occured 17 times
13 Occured 12 times

从上面的输出中,我们可以看到 rand() 函数经常可以生成可重复的数字。

sand(n) 用于使用给定参数 n 初始化随机数生成。 每当程序开始执行时,awk 就开始从 n 生成随机数。 如果没有给出参数,awk 将使用一天中的时间来生成种子。

生成 5 个从 5 到 50 的随机数:

$ cat srand.awk
BEGIN {
    # Initialize the seed with 5.
    srand(5);
    # Totally I want to generate 5 numbers.
    total=5;
    #maximum number is 50.
    max=50;
    count=0;
    while(count < total) {
        rnd = int(rand() * max);
        if ( array[rnd] == 0 ) {
            count++;
            array[rnd]++;
        }
    }
    for ( i=5; i<=max; i++) {
        if ( array[i] )
            print i;
    }
}

$ awk -f srand.awk
9
15
26
37
39

上面的 「srand.awk」 执行以下操作:

  • 使用 rand() 函数生成一个随机数,将该随机数与最大期望值相乘,得到 < 50 的数字。
  • 检查生成的随机数是否已存在于数组中。 如果不存在,则会增加索引和循环计数。 它使用此逻辑生成 5 个数字。
  • 最后在 for 循环中,它从最小值循环到最大值,并打印包含任意值的每个索引。