what is rand algorithim depending on srand and seed?

陌路散爱 提交于 2021-01-29 08:50:39

问题


When I running this code

while ...
 srand (1);
 printf ("Again the first number: %d\n", rand()%100);

on 2 PCs I get different results. but in each PC I get always the same random list.

For ex. in PC 1 I always get 83,86,77,15,93,35 and in PC2 I always get F, G ,H , I ,J.

I want to know what is the algorithim? If I know the first random , is there any way to know the second random in same PC? .

Second random is depending on seed or only on the last random?

I not to put srand(time(0)); to get a really random number , that not my problem, I only want to know if the second random number depending on input of srand +the first random number or not .


回答1:


A PRNG (pseudo random number generator) is actually some deterministic calculation that calculates the next value from some internal state, updating this state as well. So, the numbers only look random, and starting from the same internal state, you get the same sequence of numbers.

The following part isn't needed any more after the question was edited, leaving it here for reference:


Seeding a PRNG initializes this internal state. Therefore you should seed only once in your program.

If you seed with a fixed value, you get the same sequence in every run, which might be good for testing.

For your final program, seed with something that will be different on every run. The typical line in a C program is

srand(time(0));

which uses the current time for seeding. You need #include <time.h> to do this.


If I know the first random , is there any way to know the second random in same PC?

In general, no. As explained above, a good PRNG uses additional internal state, or, put the other way around, only returns part of its state as the "random number".

Here's a very simple example implementation:

static unsigned long long int randval = 1;

void srand(unsigned int seed)
{
    randval = seed;
}

int rand(void)
{
    randval *= 1103515245;
    randval += 12345;
    return (int)((randval / 65536) & 0x7fffffff);
}

Your C library probably has something more sophisticated, but it helps to understand the concept: The internal state here is long long (which has at least 64 bits), but rand() only ever returns 31 bits of it.




回答2:


The algorithm is determined by the library , In most(if not all) cases the function that produced the resulting numbers are dependent on the program heap+stack memory address , so in your case the results are not different from one pc to another but from one location in ram to another, every new random generated is dependent upon the last random number and sometimes the seed value also involved in the calculation (prefered), only the first number is calculated only with the seed value.



来源:https://stackoverflow.com/questions/51651185/what-is-rand-algorithim-depending-on-srand-and-seed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!