Float epsilon 在 C++ 中不同于 C#

Float epsilon is different in c++ than c#

这么小的问题,出于性能原因,我一直在考虑将我的部分 C# 代码移动到 C++。 现在,当我在 C# 中查看我的 float.Epsilon 时,它的值与我的 C++ 值不同。

在 C# 中,by microsoft 描述的值是 1.401298E-45。

在 C++ 中,by cppreferences 描述的值是 1.19209e-07;

float/single 的最小可能值在这些语言之间怎么可能不同?

如果我是正确的,二进制值在字节数方面应该是相等的,甚至可能是它们的二进制值。还是我看错了?

希望有人能帮帮我,谢谢!

您引用的第二个值是 IEEE binary32 值的 machine epsilon

您引用的第一个值 不是 机器 epsilon。根据您链接的文档:

The value of the Epsilon property is not equivalent to machine epsilon, which represents the upper bound of the relative error due to rounding in floating-point arithmetic.

来自wiki Variant Definitions section for machine epsilon

The IEEE standard does not define the terms machine epsilon and unit roundoff, so differing definitions of these terms are in use, which can cause some confusion.

...

The following different definition is much more widespread outside academia: Machine epsilon is defined as the difference between 1 and the next larger floating point number.

C# 文档正在使用该变体定义。

所以答案是您正在比较两种不同类型的 Epsilon。

C++

Returns the machine epsilon, that is, the difference between 1.0 and the next value representable by the floating-point type T. https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon

C#

Represents the smallest positive Single value that is greater than zero. This field is constant. https://docs.microsoft.com/en-us/dotnet/api/system.single.epsilon?view=net-5.0

结论

C# 的下一个值从 0 开始,C++ 的下一个值从 1 开始。两个完全不同的东西。

编辑:另一个答案可能更正确

从您引用的 link 中,如果您想要类似于 .NET Single.Epsilon(“最小浮点数”)的值,则应使用值 FLT_TRUE_MIN(“浮点数的最小正值”)大于零的正单个值").