问题描述
我有一个函数应该以随机方式初始化矩阵的值,给定一个概率(在这种情况下 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() 为种子时,它必须产生相同的值序列.
这部分解释了我们为什么使用time(0)
:
and this part explains why we use time(0)
:
标准做法是将调用 time(0) 的结果用作种子.但是 time() 返回一个 time_t 值,time_t 不保证是整数类型.但实际上,每个主要实现都将 time_t 定义为整数类型,这也是 POSIX 所要求的.
这篇关于带有 rand 的函数始终以相同的方式初始化矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!