Mathf.Approximately(0.0f, float.Epsilon) == true 是正确的行为吗? [英] Is Mathf.Approximately(0.0f, float.Epsilon) == true its correct behavior?
问题描述
我刚刚注意到以下代码返回 true:
I have just noticed that the following code returns true:
Mathf.Approximately(0.0f, float.Epsilon); // true
我已阅读 Mathf.Approximately 文档 并指出:
Approximately() 比较两个浮点数,如果它们在彼此的小值 (Epsilon) 内,则返回 true.
Approximately() compares two floats and returns true if they are within a small value (Epsilon) of each other.
Mathf.Epsilon 文档 指出:
- anyValue + Epsilon = anyValue
- anyValue - Epsilon = anyValue
- 0 + Epsilon = Epsilon
- 0 - Epsilon = -Epsilon
结果,我运行了以下代码,期望它是 false
,但它也返回 true
.
As a result, I ran the following code, expecting it to be false
, but it also returns true
.
Mathf.Approximately(0.0f, 2.0f * float.Epsilon); // true
顺便说一句:
Mathf.Approximately(0.0f, 2.0f * float.Epsilon); // true
Mathf.Approximately(0.0f, 3.0f * float.Epsilon); // true
Mathf.Approximately(0.0f, 4.0f * float.Epsilon); // true
Mathf.Approximately(0.0f, 5.0f * float.Epsilon); // true
Mathf.Approximately(0.0f, 6.0f * float.Epsilon); // true
Mathf.Approximately(0.0f, 7.0f * float.Epsilon); // true
Mathf.Approximately(0.0f, 8.0f * float.Epsilon); // false
Mathf.Approximately(0.0f, 9.0f * float.Epsilon); // false
<小时>
问:根据这些证据,我可以肯定地说 Mathf.Approximately
没有根据其文档*正确实现吗?
Q: Based on that evidence, can I safely say that Mathf.Approximately
is not correctly implemented according to its documentation*?
(* 因此,我应该转向不同的解决方案,例如 C# 的浮点比较函数)
(* and as a result, I should move to different solutions, such as the one in Floating point comparison functions for C#)
推荐答案
这里是Unity的public static bool Mathf.Approximately(float a, float b);
的反编译代码你可以在末尾看到 * 8.0f
^^,所以确实是一个真正糟糕的记录方法.
Here is the decompiled code of Unity's public static bool Mathf.Approximately(float a, float b);
You can see the * 8.0f
at the end ^^, so a truely badly documented method indeed.
/// <summary>
/// <para>Compares two floating point values if they are similar.</para>
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
public static bool Approximately(float a, float b)
{
return (double) Mathf.Abs(b - a) < (double) Mathf.Max(1E-06f * Mathf.Max(Mathf.Abs(a),
Mathf.Abs(b)), Mathf.Epsilon * 8.0f);
}
这篇关于Mathf.Approximately(0.0f, float.Epsilon) == true 是正确的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!