【问题标题】:rand() seeding with time() problemrand() 播种与 time() 问题
【发布时间】:2011-04-11 05:55:14
【问题描述】:

我很难弄清楚如何使用 rand() 并使用 Xcode 用 time() 播种它。我想生成 0 到 1 之间的随机十进制数。

代码为元素 1 和 2 提供了看似随机的数字,但元素 0 总是在 0.077 左右。任何想法为什么会这样?

我的代码是:

#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);
}

多次运行的输出如下:

[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.

【问题讨论】:

    标签: c time random


    【解决方案1】:

    尝试随机化随机生成器而不将其投射到 in

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

    Holly molly……这并不容易。我记得很久以前在我的随机模型中我遇到了这个问题。据我所知,解决方案是使用一些 pragma derective。

    无论如何,以下是解决方案,并且有效。每次都是随机数……不过有点俗气。

    #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);
    }
    

    【讨论】:

    • 嗯,它现在始终为元素 0 提供 0.086,但对于后两个元素仍然是随机的。
    • 哦,你很聪明。只需跳过第一个值 =]。非常感谢!
    【解决方案2】:

    典型的rand 实现并不是很好。您可以丢弃前几个结果,或者您可以切换到更好的伪随机数生成器。另请参阅:comp.lang.c 常见问题解答中的I need a random number generator.

    【讨论】:

      【解决方案3】:

      rand() 通常是一个线性同余生成器。我怀疑是rand-fbsd.c。 time() 也不是一个很好的种子,因为只有底部的几位在短时间内发生显着变化。

      random() 好一点。还可以考虑使用 sranddev() 或 srandomdev() 播种。

      【讨论】:

        猜你喜欢
        • 2015-09-15
        • 2018-11-12
        • 2012-10-24
        • 2020-03-18
        • 1970-01-01
        • 2016-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多