带有 rand 的函数始终以相同的方式初始化矩阵 [英] function with rand initializes matrix always the same way

查看:37
本文介绍了带有 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!

推荐答案

你需要调用 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() 之前使用了 rand(),则 rand() 的行为就像是使用 srand(1) 播种一样.每次 rand() 以 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.

这部分解释了我们为什么使用time(0):

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

标准做法是将调用 time(0) 的结果用作种子.但是 time() 返回一个 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天全站免登陆