在这种情况下如何设置随机矩阵?

时间:2022-09-28 16:59:31

Recently I saw link on this site

最近我在这个网站上看到了链接

Sweeping through a 2d arrays using pointers with boundary conditions

使用具有边界条件的指针扫描2d数组

Here, in "answers", is a code of boundary conditions in Ising Model. This code generate a matrix with all spins up:

这里,在“答案”中,是伊辛模型中的边界条件代码。此代码生成一个包含所有旋转的矩阵:

for (i=0; i<Lattice_Size; i++)  {  
    for (j=0; j<Lattice_Size; j++) {
        *ptr++ = spin_up;   // initializing to parallel spins,      
                            // where spin_up is an integer number
                            // taking value = +1.
    }
}

My question is: How one can set up a random configuration (matrix) with random distribution of spin_up / spin_down spins?

我的问题是:如何设置随机分配spin_up / spin_down旋转的随机配置(矩阵)?

I thought it might be done with the help of function random(...), but I figured out that I don't understand well how it works :(

我认为它可以在函数随机(...)的帮助下完成,但我发现我不太清楚它是如何工作的:(

1 个解决方案

#1


2  

You could use the function rand modulo 2:

你可以使用函数rand modulo 2:

srand(time(NULL)) ; // Initialize the rand see

for (i=0; i < Lattice_Size; i++)  {  
    for (j=0; j < Lattice_Size; j++) {
        *ptr++ = 1 - 2 * (rand() % 2); // Return either 1 or - 1
    }
}

Don't forget to include time.h and stdlib.h.

不要忘记包含time.h和stdlib.h。

  1. rand() returns a number in the range between 0 and RAND_MAX
  2. rand()返回0到RAND_MAX之间的数字
  3. rand() % 2 returns either 0 or 1
  4. rand()%2返回0或1
  5. 2 * (rand() % 2) returns either 0 or 2
  6. 2 *(rand()%2)返回0或2
  7. 1 - 2 * (rand() % 2) returns -1 or 1.
  8. 1 - 2 *(rand()%2)返回-1或1。

If you are not familiar with it, % is the modulo operator.

如果您不熟悉它,%是模运算符。

#1


2  

You could use the function rand modulo 2:

你可以使用函数rand modulo 2:

srand(time(NULL)) ; // Initialize the rand see

for (i=0; i < Lattice_Size; i++)  {  
    for (j=0; j < Lattice_Size; j++) {
        *ptr++ = 1 - 2 * (rand() % 2); // Return either 1 or - 1
    }
}

Don't forget to include time.h and stdlib.h.

不要忘记包含time.h和stdlib.h。

  1. rand() returns a number in the range between 0 and RAND_MAX
  2. rand()返回0到RAND_MAX之间的数字
  3. rand() % 2 returns either 0 or 1
  4. rand()%2返回0或1
  5. 2 * (rand() % 2) returns either 0 or 2
  6. 2 *(rand()%2)返回0或2
  7. 1 - 2 * (rand() % 2) returns -1 or 1.
  8. 1 - 2 *(rand()%2)返回-1或1。

If you are not familiar with it, % is the modulo operator.

如果您不熟悉它,%是模运算符。