[英]Check if a value hasn't changed more than 10^-3?
所以我有两个带有几个值的迭代,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");
}
有什么建议?
提前致谢。
编辑:代码格式
正如评论中提到的,如果您正在寻找更改,您可能意味着增加或减少。
if((firstX - x) < Math.pow(10, -3))
此行仅检查两者之一。 如果您使用整数,请尝试将其替换为Math类中的以下内容。 这是java.lang.Math
一部分,不需要导入。
if(Math.abs(firstX - x) < Math.pow(10, -3))
如果在代码中重复引用Math.pow(10, -3)
或频繁调用检查以提高可读性(如果是热点,则提高性能Math.pow(10, -3)
,您可能还想考虑将它放在常量中。
@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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.