rand() seeding with time() problem

人走茶凉 提交于 2020-01-04 04:06:05

问题


I'm having difficulty figuring out how to use rand() and seeding it with time() using Xcode. I want to generate random decimal numbers between 0 and 1.

The code gives me seemingly random numbers for elements 1 and 2, but element 0 is always somewhere around 0.077. Any ideas why this would be?

My code is:

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

int main(void)
{
double array[3];

double rand_max = RAND_MAX;

srand((int)time(NULL));

for (int iii = 0; iii < 3; iii++)
    array[iii] = rand() / rand_max;

for (int iii = 0; iii < 3; iii++)
    printf("Element %d is: %lf.\n", iii, array[iii]);

return(0);
}

The output for several runs was as follows:

[Session started at 2010-09-11 21:19:07 -0500.]

Element 0 is: 0.076918.

Element 1 is: 0.753664.

Element 2 is: 0.824467.

The Debugger has exited with status 0.
[Session started at 2010-09-11 21:19:12 -0500.]
Element 0 is: 0.076957.
Element 1 is: 0.411353.
Element 2 is: 0.602494.

The Debugger has exited with status 0.

[Session started at 2010-09-11 21:19:16 -0500.]

Element 0 is: 0.076988.

Element 1 is: 0.937504.

Element 2 is: 0.624915.

The Debugger has exited with status 0.

[Session started at 2010-09-11 21:19:24 -0500.]

Element 0 is: 0.077051.

Element 1 is: 0.989806.

Element 2 is: 0.669757.

回答1:


Typical rand implementations simply aren't very good. You could throw away the first few results, or you could switch to a better pseudo-random number generator. Also see: I need a random number generator. from the comp.lang.c FAQ.




回答2:


try randomize random generator without casting it to in

/* initialize random seed: */
srand ( time(NULL) );

Holly molly... this one is not easy. I remember long time ago in my stochastic models I had this problem. The solution was to use some pragma derective, as far as I remember.

anyways below is solution and it works. Random numbers every time... kind of cheezy though.

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

int main(void)
{
    double array[10];

    double rand_max = RAND_MAX;

    srand(time(NULL));

    for (int iii = 0; iii < 9; iii++){
        rand();
        array[iii] = rand() / rand_max;
    }

    for (int iii = 0; iii < 9; iii++){
        printf("Element %d is: %lf.\n", iii, array[iii]);
    }


    return(0);
}



回答3:


rand() is usually a linear congruential generator. I suspect it's rand-fbsd.c. time() is not a very good seed either, since only the bottom few bits change significantly over a short time.

random() is a bit better. Also consider seeding using sranddev() or srandomdev().



来源:https://stackoverflow.com/questions/3693511/rand-seeding-with-time-problem

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