public static void main(String[] args) {
double s = 0; //Position
double v = 100; //Velocity
double g = 9.81; //Gravitational Force
for(double time = 0.01; time < 100; time = time + 0.01){
double DELTA_T = 0.01;
s = s + (v * DELTA_T);
v = v - (g * DELTA_T);
if(time % 1 == 0) { //I want to print this out, but it seems to end the program with no output
System.out.println("Seconds: " + time);
System.out.println("Position: " + s);
System.out.println("Velocity: " + v);
}
}
}我想在(time %1 == 0)时输出计算结果。但是当我运行它的时候,它没有打印出任何东西。当我删除if语句并保留在print语句中时,它将打印出来。
我想知道我的if语句出了什么问题,我该如何尝试每次打印"s“、"v”和" time“(time %1 == 0)
发布于 2020-03-04 04:31:18
这里的问题很可能是因为您正在比较浮点值的相等性。有关我们在浮点数学和等式比较中遇到的问题,请参阅Is floating point math broken?。
对于您的特定问题,我建议您使用表示百分之一秒的整数计数器。然后,您可以使用整数进行比较:
public static void main(String[] args) {
double s = 0; //Position
double v = 100; //Velocity
double g = 9.81; //Gravitational Force
for(int time = 1; time < 10000; time++) {
double DELTA_T = 0.01;
s = s + (v * DELTA_T);
v = v - (g * DELTA_T);
if(time % 100 == 0) { //I want to print this out, but it seems to end the program with no output
System.out.println("Seconds: " + time);
System.out.println("Position: " + s);
System.out.println("Velocity: " + v);
}
}
}这将解决您的打印问题。但是,您最希望看到的是s和v没有正确的值。这是因为您在每次迭代中都会累积浮点数学中的错误。您应该在每次迭代时直接从time计算这些值,而不是现在这样做。
发布于 2020-03-04 04:51:05
你的时变精度正在毁掉你的模数检查。你需要乘法并强制转换为int,才能得到一个好的结果:
public static void main(String [] args {
double s = 0; //Position
double v = 100; //Velocity
final double g = 9.81; //Gravitational Force
final double DELTA_T = 0.01;
for(double time = 0.01; time < 100; time += 0.01){
s += (v * DELTA_T);
v -= (g * DELTA_T);
System.out.println(time);
if (((int) (time * 100)) % 100 == 0) {
System.out.println("Seconds: " + time);
System.out.println("Position: " + s);
System.out.println("Velocity: " + v);
}
}
}https://stackoverflow.com/questions/60514956
复制相似问题