作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Strawberry Perl
v5.16.2
使用重复调用 int rand 1_000_000
来构造一些虚假数据.之后,相当困惑,我发现因为我的 perl 的 randbits=15
, 上面的表达式只会返回 2**15
或 32768
可能的值。
>perl -V:randbits
randbits='15';
use warnings;
当有人尝试使用 rand $val
时不返回警告在哪里 $val > 2 ** randbits
? perldoc rand
根本不提这个问题?有一个关于如何 "rand() is not cryptographically secure"
的附录.我相信这也值得附上建议的替代解决方案。 p
在 2000 万次拉取中不会选择小于 100 万的特定整数是
(999_999/1_000_000) ** 20_000_000
或
2.06e-9
.所以不会选择任何整数的概率是
.2%
.
use strict;
use warnings;
use List::Util qw(sum max min);
our $max_count = 1_000;
my %count;
while (1) {
my $val = int rand 1_000_000;
last if ++$count{$val} > $max_count;
}
my $sum = sum values %count;
my $max = max values %count;
my $min = min values %count;
my $count = scalar keys %count;
print "$sum interations. $count integers of expected 1mil with min $min, max $max\n";
28,958,579 interations. 32768 integers of expected 1mil with min 772, max 1001
32,768
是一个巨大的红旗,是
2
的力量,所以快速谷歌搜索
"perl rand does maximum 32768 integers"
返回以下有用资源:
What is wrong with perl's antique random number generator
How big can the argument to Perl's rand be? - Stack Overflow
rand
与
use Math::Random::MT qw(rand);
和
use Math::Random::MT::Auto qw(rand);
.
an answer
其中包括一个不需要安装新模块的解决方案,只需调用
rand
两次以获得更多位。
use Config;
use constant RANDBITS => $Config{randbits};
use constant RAND_MAX => 2**RANDBITS;
sub double_rand {
my $max = shift || 1;
my $iv =
int rand(RAND_MAX) << RANDBITS
| int rand(RAND_MAX);
return $max * ($iv / 2**(2*RANDBITS));
}
rand
的替代品有更好的下降吗? ? perldoc rand
为什么没有两句附录提到这个问题? warnings
大于 2**randbits
的值不发出警告?如果有人想忽略警告,可能会有 no warnings 'rand'
调用或直接调用没有值的 rand:val * rand
. 最佳答案
对于非加密目的,请使用 Math::Random::MT . The Mersenne Twister PRNG有很好的属性。
您可以使用函数接口(interface)作为 rand
的替代品。内置:
面向函数的界面:
use Math::Random::MT qw(srand rand irand);
# now use srand() and rand() as you usually do in Perl
关于perl - 为什么 $val > 2 ** randbits 时 rand($val) 不发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22772578/
我正在使用 Strawberry Perl v5.16.2使用重复调用 int rand 1_000_000 来构造一些虚假数据.之后,相当困惑,我发现因为我的 perl 的 randbits=15
我是一名优秀的程序员,十分优秀!