System.Decimal是否一致?

时间:2012-12-12 08:28:45

标签: c# .net floating-point ieee-754

使用浮点数或双精度数的浮点计算在硬件上执行,这可能会在不同的体系结构或优化设置上产生不同的结果,如here所述。

在该线程中简要提及但未完全回答的一件事是System.Decimal的情况。有人提到System.Decimal 可能用作一致的浮点类型,它会非常慢,并且.NET(System.Math)提供的数学函数没有实现System.Decimal。

我能找到的关于这种类型的唯一信息是Marc Gravell saying它是用软件实现的,这强烈暗示它确实是一致的。

我的问题是:可以使用System.Decimal在所有硬件平台上获得一致的结果,还是容易出现与System.Single和System.Double相同的问题?

如果System.Decimal是一致的,是否有任何免费的库为它实现超越函数(cos,sin,tan,sqrt,log等)?

1 个答案:

答案 0 :(得分:2)

以一种方式保持一致,它将在所有.NET实现上产生相同的结果是。

以一种始终代表操作号的正确结果的方式保持一致。任何浮点都会有代表某些价值的麻烦。 System.Decimal只能准确地表示那些准确表示为十进制值E.g的数字。 1/3将被错误地表示为0.33333 ......并且cos,sin,tan,sqrt和log的许多结果将是近似值,因为存在任何数字系统(例如十进制或二进制) )是很多值,只能表示为最接近的近似值。

C#规范说: The result of an operation on values of type decimal is that which would result from calculating an exact result (preserving scale, as defined for each operator) and then rounding to fit the representation. Results are rounded to the nearest representable value, and, when a result is equally close to two representable values, to the value that has an even number in the least significant digit position.

相关问题