Is .NET “decimal” arithmetic independent of platform/architecture?

后端 未结 4 942
栀梦
栀梦 2021-01-04 03:13

I asked about System.Double recently and was told that computations may differ depending on platform/architecture. Unfortunately, I cannot find any information

4条回答
  •  感情败类
    2021-01-04 03:43

    Even though the format of floating point types is clearly defined, floating point calculations can indeed have differing results depending on architecture, as stated in section 4.1.6 of the C# specification:

    Floating-point operations may be performed with higher precision than the result type of the operation. For example, some hardware architectures support an “extended” or “long double” floating-point type with greater range and precision than the double type, and implicitly perform all floating-point operations using this higher precision type. Only at excessive cost in performance can such hardware architectures be made to perform floating-point operations with less precision, and rather than require an implementation to forfeit both performance and precision, C# allows a higher precision type to be used for all floating-point operations.

    While the decimal type is subject to approximation in order for a value to be represented within its finite range, the range is, by definition, defined to be suitable for financial and monetary calculations. Therefore, it has a higher precision (and smaller range) than float or double. It is also more clearly defined than the other floating point types such that it would appear to be platform-independent (see section 4.1.7 - I suspect this platform independence is more because there isn't standard hardware support for types with the size and precision of decimal rather than because of the type itself, so this may change with future specifications and hardware architectures).

    If you need to know if a specific implementation of the decimal type is correct, you should be able to craft some unit tests using the specification that will test the correctness.

提交回复
热议问题