与Rand函数总是初始化矩阵以同样的方式 [英] function with rand initializes matrix always the same way

查看:149
本文介绍了与Rand函数总是初始化矩阵以同样的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有给定的概率应该初始化以随机方式矩阵的值的函数,(在这种情况下,P(0)= 1/3,P(1)= 2/3)
的问题是,矩阵总是出来是相同的:

I have a function that should initialize the values of matrix in a random way, given a probability (in this case p(0)=1/3, p(1) = 2/3 ) The problem is that the matrix always comes out to be the same:

void init_matrix(short unsigned* m,int* n_gen)
{
    *n_gen=0;
    int i;
    for(i=0;i<N_X*N_Y;i++) {
        if( ( ( rand() % 100 ) % 3) == 0 )
            m[i]=0;
        else
            m[i]=1;
     }
}

是不是因为rand()函数的执行?还是我用它不正确?谢谢!

is it because of the implementation of the rand() function? Or am I using it incorrectly? Thanks!

推荐答案

您需要调用的在code的初始段函数srand 以初始化随机数发生器,如文件显示,这是调用的的函数srand 的典型方式:

You need to call srand in the initial section of your code in order to initialize your random number generator, as the document shows this is typical ways of calling srand:

srand(time(0));

作为文档说明:

如果兰特()的任何调用之前使用srand()函数,兰特()的行为就好像是用函数srand种子(1)。每次兰特()接种用srand()函数,它必须产生的值的相同序列。

If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values.

和这部分解释了为什么我们使用时间(0)

and this part explains why we use time(0):

标准的做法是使用一个呼叫的结果时间(0)作为种子。然而,时间()返回一个time_t的值,time_t的是不能保证是整型。但在实践中,每一个主要的实现定义的time_t是一个整数类型,这也是什么POSIX需要。

Standard practice is to use the result of a call to time(0) as the seed. However, time() returns a time_t value, and time_t is not guaranteed to be an integral type. In practice, though, every major implementation defines time_t to be an integral type, and this is also what POSIX requires.

这篇关于与Rand函数总是初始化矩阵以同样的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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