如何做浮点比较?我目前正在编写一些代码,其中有如下内容:double a = SomeCalculation1();double b = SomeCalculation2();if (a < b)
DoSomething2();else if (a > b)
DoSomething3();然后在其他地方,我可能需要做平等:double a = SomeCalculation3();double b = SomeCalculation4();if (a == 0.0)
DoSomethingUseful(1 / a);if (b == 0.0)
return 0; // or something else here总之,我有很多浮点的数学,我需要做各种条件的比较。我不能把它转换成整数数学,因为在这个上下文中,这样的事情是没有意义的。我以前读过浮点比较可能是不可靠的,因为您可以这样做:double a = 1.0 / 3.0;double b = a + a + a;if ((3 * a) != b)
Console.WriteLine("Oh no!");简而言之,我想知道:如何可靠地比较浮点数(小于,大于等于)?我使用的数字范围大概在10e-14到10E6之间,所以我确实需要处理小数字和大数字。我将此标记为语言不可知论者,因为无论我使用哪种语言,我都对如何实现这一目标感兴趣。
3 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
public static boolean nearlyEqual(float a, float b, float epsilon) { final float absA = Math.abs(a); final float absB = Math.abs(b); final float diff = Math.abs(a - b); if (a == b) { // shortcut, handles infinities return true; } else if (a == 0 || b == 0 || diff < Float.MIN_NORMAL) { // a or b is zero or both are extremely close to it // relative error is less meaningful here return diff < (epsilon * Float.MIN_NORMAL); } else { // use relative error return diff / (absA + absB) < epsilon; }}
月关宝盒
TA贡献1772条经验 获得超5个赞
A < B
A > B
if(A - B < Epsilon) && (fabs(A-B) > Epsilon){ printf("A is less than B");}if (A - B > Epsilon) && (fabs(A-B) > Epsilon){ printf("A is greater than B");}
MM们
TA贡献1886条经验 获得超2个赞
final float TOLERANCE = 0.00001;if (Math.abs(f1 - f2) < TOLERANCE) Console.WriteLine("Oh yes!");
double a = 1.0 / 3.0;double b = a + a + a;if (a != b) Console.WriteLine("Oh no!");
a = 1/3b = 1/3 + 1/3 + 1/3 = 1.1/3 != 1
if (b != 1) Console.WriteLine("Oh no!")
添加回答
举报
0/150
提交
取消