gpt4 book ai didi

java - 6 次迭代后,在 for 循环中将新值赋给 double

转载 作者:行者123 更新时间:2023-12-02 00:29:16 25 4
gpt4 key购买 nike

我不明白为什么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 次某事。在循环中创建另一个循环只会添加更多某事的迭代;相反,尝试检查外部循环上的计数器。

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

关于java - 6 次迭代后,在 for 循环中将新值赋给 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58029612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com