在 6 次迭代后,在 for 循环中为 double 分配新值
Assign new value to double in a for loop after 6 iterations
我不明白为什么 x=x-z
给我这样的值。
x
应该每 6 次循环将其值减少 z
,对于 1000 次循环,使得 mrnd
(数学随机)大于 poa
(概率验收)。
int i = 0;
double y = 0.9;
double x = 1.0;
double z = 0.1;
for (int o = 0; o < 1000; o++) {
for (i = 0; i < 6; i++) {
Double random = Math.random();
Double mrnd = Math.floor(random*100)/100;
double poa = (x*y);
System.out.println("randomkalk " + mrnd);
System.out.println("probability" + poa);
if (poa < mrnd ) {
System.out.println("accept change");
};
if (poa > mrnd ) {
System.out.println("deny change");
}
}
System.out.println(x-z); // This gives the right output if x=x-z is not present
System.out.println(" nr 6 \n \n ");
x = x-z; // Gives wrong output
}
正如 M. Prokhorov 指出的那样,您没有在每 6 次迭代中做任何事情。你每次迭代都在做 6 次。在循环中创建另一个循环只会增加 something 的更多迭代;相反,请尝试检查外部循环中的计数器。
int i = 0;
double y = 0.9;
double x = 1.0;
double z = 0.1;
for (int o = 0; o < 1000; o++) {
Double random = Math.random();
Double mrnd = Math.floor(random*100)/100;
double poa = (x*y);
System.out.println("randomkalk " + mrnd);
System.out.println("probability" + poa);
if (poa < mrnd ) {
System.out.println("accept change");
};
if (poa > mrnd ) {
System.out.println("deny change");
}
if (o % 6 == 5) {
x = x-z;
}
}
在这里,我使用取模运算符来检查我们是否在第 6 次迭代
- 0 % 6 == 0
- 1 % 6 == 1
- 2 % 6 == 2
- 3 % 6 == 3
- 4 % 6 == 4
- 5 % 6 == 5 递减
- 6 % 6 == 0
- 7 % 6 == 1
- 8 % 6 == 2
- 9% 6 == 3
- 10% 6 == 4
- 11 % 6 == 5 递减
- 12% 6 == 0
我不明白为什么 x=x-z
给我这样的值。
x
应该每 6 次循环将其值减少 z
,对于 1000 次循环,使得 mrnd
(数学随机)大于 poa
(概率验收)。
int i = 0;
double y = 0.9;
double x = 1.0;
double z = 0.1;
for (int o = 0; o < 1000; o++) {
for (i = 0; i < 6; i++) {
Double random = Math.random();
Double mrnd = Math.floor(random*100)/100;
double poa = (x*y);
System.out.println("randomkalk " + mrnd);
System.out.println("probability" + poa);
if (poa < mrnd ) {
System.out.println("accept change");
};
if (poa > mrnd ) {
System.out.println("deny change");
}
}
System.out.println(x-z); // This gives the right output if x=x-z is not present
System.out.println(" nr 6 \n \n ");
x = x-z; // Gives wrong output
}
正如 M. Prokhorov 指出的那样,您没有在每 6 次迭代中做任何事情。你每次迭代都在做 6 次。在循环中创建另一个循环只会增加 something 的更多迭代;相反,请尝试检查外部循环中的计数器。
int i = 0;
double y = 0.9;
double x = 1.0;
double z = 0.1;
for (int o = 0; o < 1000; o++) {
Double random = Math.random();
Double mrnd = Math.floor(random*100)/100;
double poa = (x*y);
System.out.println("randomkalk " + mrnd);
System.out.println("probability" + poa);
if (poa < mrnd ) {
System.out.println("accept change");
};
if (poa > mrnd ) {
System.out.println("deny change");
}
if (o % 6 == 5) {
x = x-z;
}
}
在这里,我使用取模运算符来检查我们是否在第 6 次迭代
- 0 % 6 == 0
- 1 % 6 == 1
- 2 % 6 == 2
- 3 % 6 == 3
- 4 % 6 == 4
- 5 % 6 == 5 递减
- 6 % 6 == 0
- 7 % 6 == 1
- 8 % 6 == 2
- 9% 6 == 3
- 10% 6 == 4
- 11 % 6 == 5 递减
- 12% 6 == 0