简体   繁体   English

C++浮点比较

[英]C++ float comparison

I want to compare floats.我想比较浮动。 I had a problem when comparing equality so I used epsilon and it was solved我在比较相等性时遇到了问题,所以我使用了 epsilon 并解决了

inline bool isEqual(float x, float y)
{
  const float epsilon = 1e-5;
  return abs(x - y) <= epsilon * abs(x);
}

but I also want to compare other comparisons such as '>' and '<='但我也想比较其他比较,例如 '>' 和 '<='

I have two floats = 49 but when executing f1 > f2 it returns true.我有两个浮点数 = 49 但在执行f1 > f2它返回 true。

I have tried this function:我试过这个功能:

inline bool isSmallerOrEqual(float x, float y)
{
  const float epsilon = 0.01;
  return epsilon * abs(x) <= epsilon * abs(y);
}

It worked but not for all values.它有效,但不适用于所有值。 Any ideas ?有任何想法吗 ?

First, your isEquals function may be wrong, you're using the relative epsilon version.首先,您的isEquals函数可能是错误的,您使用的是相关的 epsilon 版本。 This version is works better with extremely large numbers, but breaks down when using extremely small numbers.这个版本在处理非常大的数字时效果更好,但在使用非常小的数字时会崩溃。 The other version would be to use absolute epsilon.另一个版本是使用绝对 epsilon。 This version works well with small numbers (including extremely small numbers), but breaks down with extremely large numbers.此版本适用于小数字(包括极小的数字),但对于极大的数字会崩溃。

inline bool epsilonEquals(const float x, const float y, const float epsilon = 1E-5f)
{
    return abs(x - y) <= epsilon;
}

Second, calling it isEquals is inaccurate, the function is generally known as Epsilon Equals because it doesn't validate that 2 numbers are equal, it validates that they are reasonably close to each other within a small margin of error (epsilon).其次,调用isEquals是不准确的,该函数通常称为Epsilon Equals,因为它不验证 2 个数字是否相等,而是验证它们在很小的误差范围 (epsilon) 内彼此相当接近。

Third, if you want to check that 2 numbers are less than or equal to each other then you generally don't need or even want an epsilon equals function involved, doing so only increases the likelihood of false positive.第三,如果您想检查 2 个数字是否小于或等于彼此,那么您通常不需要甚至不需要 epsilon 等于函数,这样做只会增加误报的可能性。 If you do want to use epsilon comparison you can take advantage of paulmckenzie's method:如果您确实使用 epsilon 比较,您可以利用 paulmckenzie 的方法:

inline bool epsilonLessThanOrEqualTo(const float x, const float y, const float epsilon = 1E-5f)
{
    return x <= y || epsilonEquals(x, y, epsilon);
}

If you want to have an epsilon not-equals method you can simply check that the absolute difference between the 2 numbers is larger than epsilon.如果你想要一个 epsilon 不等于方法,你可以简单地检查两个数字之间的绝对差是否大于 epsilon。

I was trying to add float values (all have one precision) through for loop, and then compare the result value with a normal declared float.我试图通过 for 循环添加浮点值(都具有一个精度),然后将结果值与正常声明的浮点数进行比较。 But I was not getting the answers right.但我没有得到正确的答案。

I solved it by converting the floats to int by multiplying each with 10, then compare it with value*10我通过将每个浮点数乘以 10 将浮点数转换为 int 来解决它,然后将其与 value*10 进行比较

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM