所以我有两次迭代,只有几个值,x是最重要的一个。我必须使用双精度,而不是整数。
我需要检查第二次迭代的x值是否没有比第一次迭代中的x值变化超过10^-3。下面是代码的快速最小化预览和我尝试进行比较的if语句。不幸的是,这种比较并不像预期的那样有效。
(while z < 10) {
x = do some math stuff
z++;
}
firstX = x; // store the x value from the first iteration
z = 0;
(while z < 100) {
x = again some math stuff.
}
if((firstX - x) < Math.pow(10, -3)){
System.out.println("value hasn't changed more than 10^-3");
} else {
System.out.println("value has changed more than 10^-3");
}有什么建议吗?
提前谢谢。
编辑:代码格式
发布于 2020-11-02 02:42:21
正如评论中提到的,如果你在寻找变化,你可能是指增加或减少。
if((firstX - x) < Math.pow(10, -3))这一行只检查两个中的一个。如果您使用的是整数,请尝试将其替换为Math类中的以下内容。这是java.lang.Math的一部分,不需要导入。
if(Math.abs(firstX - x) < Math.pow(10, -3))如果Math.pow(10, -3)在代码中被重复引用,或者频繁调用检查以提高可读性(如果它是一个热点,则还需要提高性能),您可能还需要考虑将它放在一个常量中。
发布于 2020-11-02 03:42:31
@m-soyturk在评论中提到了我认为最好的方法。将10E-3作为epsilon值,应符合以下条件。
if(Math.abs(firstX - x) < 0.001){ //Math.pow() - since the epsilon is constant I am against using it. Use 0.001 or 1E-3 instead
System.out.println("value hasn't changed more than 10^-3");
} else {
System.out.println("value has changed more than 10^-3");
}https://stackoverflow.com/questions/64635517
复制相似问题