perl - perl 中的 srand 函数没有给出正确的值范围

标签 perl

我正在尝试在 perl 中使用 srand 函数,但似乎它没有经常设置种子值

#!/usr/bin/perl
srand(45);
$int = rand(50);
print "random integer is $int\n";

[root@localhost cookbook]# perl p2.7.pl 
random integer is 17.8465963028886

随机数不应该在 45 到 50 之间吗?

最佳答案

srand 种子 随机数生成器。大多数编程语言中的随机数并不是真正的随机数,但对于大多数目的来说都可以。设置种子将允许随机数序列一遍又一遍地重复。从 Perldoc:

[T]here are a few situations where programs are likely to want to call srand. One is for generating predictable results, generally for testing or debugging. There, you use srand($seed), with the same $seed each time.



这是一个示例程序:
#! /usr/bin/env perl
#
use strict;             # Lets you know when you misspell variable names
use warnings;           # Warns of issues (using undefined variables

use feature qw(say);

srand 10;
for my $count ( (1..6) ) {
    say rand 10;
}

每次我运行它时,我都会得到:
$ test.pl
8.78851122762175
7.95806622921617
4.80827281057042
5.25673258208322
4.59162474505394
9.45475794360377

一遍又一遍。那是因为我每次都使用相同的种子,允许随机数函数一遍又一遍地重复。这在测试中很有用。

去掉 srand 10 行,程序每次都会生成不同的随机数序列。

根据 Perldoc rand :

Returns a random fractional number greater than or equal to 0 and less than the value of EXPR, [the argument given]. EXPR should be positive.



它继续:

Apply int() to the value returned by rand() if you want random integers instead of random fractional numbers. For example, int(rand(10)) returns a random integer between 0 and 9 , inclusive.



因此,rand 50 返回 0 到 50(但不是 50)之间的值。也就是说,int( rand 50 ) 将返回一个 0 到 49 之间的整数。如果我想要一个 45 到 50 之间的数字,我必须首先决定 50 是否应该是我想要的数字之一。如果是,我需要六个数字的范围(45、46、47、48、49、50)。因此,我想使用 int( rand 6 ) 给我一个 0 到 5 之间的整数。然后我想加上 45 给我 45 的范围,给我 45 到 50 的范围:
say 45 + int( rand 6 );

关于perl - perl 中的 srand 函数没有给出正确的值范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27772900/

相关文章:

perl - 打开位于同一目录中的文件时出错

perl - 使用 sed、perl、awk、tr 或任何东西只删除文本文件中的单个空格

performance - 在 Perl 中高效处理所有可能的二维数组组合

缺少 Perl 参数

perl - 为什么 perl 不关心我是否在限制条件下声明了我的变量?

java - 生成线程利用率摘要

perl - 我如何以及在哪里可以了解有关 Perl 优化器的更多信息?

php - 即时创建配置文件

perl - 如何调试派生的Perl脚本

perl - 如何在 Perl 中使用哈希生成唯一 ID?