调试/发布模式中的浮点/双精度

时间:2023-05-05
本文介绍了调试/发布模式中的浮点/双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

调试模式和发布模式之间的 C#/.NET 浮点运算的精度是否不同?

Do C#/.NET floating point operations differ in precision between debug mode and release mode?

推荐答案

它们确实可以不同.根据 CLR ECMA 规范:

They can indeed be different. According to the CLR ECMA specification:

浮点的存储位置数字(静态、数组元素和类的字段)是固定大小的.支持的存储大小是浮点 32 和浮点 64.其他地方(在评估堆栈上,如参数,作为返回类型,并作为局部变量)浮点数字用一个表示内部浮点类型.每一个这种情况下,标称类型的变量或表达式是 R4 或R8,但它的值可以表示内部有额外的范围和/或精度.的大小内部浮点表示取决于实现,可能会有所不同,并且至少应具有精度与变量或表示的表达式.一个隐式扩大转换为来自 float32 的内部表示或 float64 时执行那些类型是从存储中加载的.这内部表示通常是硬件的本机大小,或根据需要高效执行操作.

Storage locations for floating-point numbers (statics, array elements, and fields of classes) are of fixed size. The supported storage sizes are float32 and float64. Everywhere else (on the evaluation stack, as arguments, as return types, and as local variables) floating-point numbers are represented using an internal floating-point type. In each such instance, the nominal type of the variable or expression is either R4 or R8, but its value can be represented internally with additional range and/or precision. The size of the internal floating-point representation is implementation-dependent, can vary, and shall have precision at least as great as that of the variable or expression being represented. An implicit widening conversion to the internal representation from float32 or float64 is performed when those types are loaded from storage. The internal representation is typically the native size for the hardware, or as required for efficient implementation of an operation.

这基本上意味着以下比较可能相等也可能不相等:

What this basically means is that the following comparison may or may not be equal:

class Foo
{
  double _v = ...;

  void Bar()
  {
    double v = _v;

    if( v == _v )
    {
      // Code may or may not execute here.
      // _v is 64-bit.
      // v could be either 64-bit (debug) or 80-bit (release) or something else (future?).
    }
  }
}

重要信息:永远不要检查浮动值是否相等.

Take-home message: never check floating values for equality.

这篇关于调试/发布模式中的浮点/双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:截断十进制数不四舍五入 下一篇:SSE 浮点算术是否可重现?

相关文章

最新文章