什么函数srand之间的差(1)和函数srand(0) [英] What‘s the difference between srand(1) and srand(0)

查看:322
本文介绍了什么函数srand之间的差(1)和函数srand(0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现硬盘的方式,函数srand(1)重置C的PRNG(++)对任何调用之前的状态函数srand (如参考定义)。
然而,种子0似乎做相同的,或任何调用函数srand 之前的状态似乎使用种子0。
什么是这两个电话或者什么的区别是,他们做同样的事情的原因是什么?

例如这个code(执行上Ideone

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释主(){
    对(INT种子= 0;种子4;种子++){
        的printf(种子%D:,种子);
        函数srand(种子);
        的for(int i = 0;我小于5;我++)
            的printf(%10D,RAND());
        的printf(\\ n);
    }
    返回0;
}

返回

  0种子:1804289383 846930886 1681692777 1714636915 1957747793
种子1:1804289383 846930886 1681692777 1714636915 1957747793
种子2:1505335290 1738766719 190686788 260874575 747983061
种子3:1205554746 483147985 844158168 953350440 612121425


解决方案

这可能是一个实现细节。该标准规定了随机种子1是特别的,并特定随机发生器算法的内部寄存器可能是零初始化,从而导致对种子(0)和种子相同的随机序列(1)。我甚至敢打赌,你的函数srand的第一行()实现是这样的:

 如果(种子== 1)种子= 0;

强制符合标准的行为。

通常,不需要用于兰特()和函数srand随机数发生器(),得到不同的序列用于不同的种子,但对于相同的种子相同的序列。因此,不依赖于不同的种子产生不同的随机序列,然后你应该罚款。如果不是,欢迎实现特定的乐趣。

I just found out the hard way that srand(1) resets the PRNG of C(++) to the state before any call to srand (as defined in the reference). However, the seed 0 seems to do the same, or the state before any call to srand seems to use the seed 0. What’s the difference between those two calls or what is the reason they do the same thing?

For example this code (execute on Ideone)

#include <stdio.h>
#include <stdlib.h>

int main() {
    for (int seed = 0; seed < 4; seed++ ) {
        printf( "Seed %d:", seed);
        srand( seed );
        for(int i = 0; i < 5; i++ )
            printf( "    %10d", rand() );
        printf( "\n");
    }
    return 0;
}

returns

Seed 0:    1804289383     846930886    1681692777    1714636915    1957747793
Seed 1:    1804289383     846930886    1681692777    1714636915    1957747793
Seed 2:    1505335290    1738766719     190686788     260874575     747983061
Seed 3:    1205554746     483147985     844158168     953350440     612121425

解决方案

It is probably an implementation detail. The standard mandates that the random seed 1 is special, and the internal register of your specific random generator algorithm is probably zero-initialized, thus causing the same random sequence for seed(0) and seed(1). I'd even wager that the first line of your srand() implementation looks like:

if ( seed == 1 ) seed = 0;

to force standard-conformant behaviour.

Generally, the random number generators for rand() and srand() are not required to give different sequences for different seeds, but the same sequence for the same seed. So, don't rely on different seeds generating different random sequences, and you should be fine. If not, welcome to implementation-specific fun.

这篇关于什么函数srand之间的差(1)和函数srand(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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