如何在 Perl 中存储伪随机生成器的状态? [英] How can I store the state of the pseudo-random generator in Perl?

查看:50
本文介绍了如何在 Perl 中存储伪随机生成器的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Perl 中存储内置伪随机数生成器的当前状态,这样当我的程序再次运行时,它可以从停止的地方获取序列,而不是从新序列开始?

Is there a way to store the current state of the built in pseudo-random number generator in Perl so that when my program is run again, it can pick up the sequence from where it left off rather than starting with a new sequence?

现在,我正在存储我所在的位置以及初始种子,然后使用类似于以下内容的方法丢弃我已经看到的初始段:

Right now, I am storing where I am as well as the initial seed and then throwing away the initial segment which I have already seen using something similar to:

sub consume_upto_n {
    my ($seed, $n) = @_;
    $n = 1 unless defined $n and $n >= 1;
    srand $seed;
    rand for 1 .. $n - 1;
    return;
}

例如:

srand 0x18;
my @v = map { rand } 1 .. 5;

后来:

consume_upto_n(0x18, 3);
my @z = map { rand } 3 .. 5;

然后,$z[0] == $v[2]$z[1] == $v[3] 等等

推荐答案

截至 perl 5.13.4srand返回种子:

As of perl 5.13.4, srand returns the seed:

srand() 现在返回种子

这允许需要具有可重复结果的程序不必提出自己的种子生成机制.相反,他们可以使用 srand() 并以某种方式隐藏返回以备将来使用.典型的测试程序有太多组合,无法在每次运行的可用时间内进行全面测试.它每次都可以测试一个随机子集,如果出现故障,请记录用于该运行的种子,以便以后可以使用它来重现准确的结果.

This allows programs that need to have repeatable results to not have to come up with their own seed generating mechanism. Instead, they can use srand() and somehow stash the return for future use. Typical is a test program which has too many combinations to test comprehensively in the time available to it each run. It can test a random subset each time, and should there be a failure, log the seed used for that run so that it can later be used to reproduce the exact results.

这篇关于如何在 Perl 中存储伪随机生成器的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆