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。
-
rand()
returns a number in the range between0
andRAND_MAX
- rand()返回0到RAND_MAX之间的数字
-
rand() % 2
returns either0
or1
- rand()%2返回0或1
-
2 * (rand() % 2)
returns either0
or2
- 2 *(rand()%2)返回0或2
-
1 - 2 * (rand() % 2)
returns-1
or1
. - 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。
-
rand()
returns a number in the range between0
andRAND_MAX
- rand()返回0到RAND_MAX之间的数字
-
rand() % 2
returns either0
or1
- rand()%2返回0或1
-
2 * (rand() % 2)
returns either0
or2
- 2 *(rand()%2)返回0或2
-
1 - 2 * (rand() % 2)
returns-1
or1
. - 1 - 2 *(rand()%2)返回-1或1。
If you are not familiar with it, %
is the modulo operator.
如果您不熟悉它,%是模运算符。