Is System.Decimal consistent?

Floating point calculations using floats or doubles are performed on equipment that can produce different results for different architectures or optimization settings, as discussed here .

One thing that was briefly mentioned in this thread but didn’t fully answer is the System.Decimal case. It was noted that System.Decimal can be used as a consistent floating point type, that it will be very slow, and that the mathematical functions offered by .NET (System.Math) were not implemented for System.Decimal.

The only other bit of information I could find about this type is Mark Gravell, who says it is implemented in software that strongly hints that it is really consistent.

My question is this: can System.Decimal be used to get consistent results on all hardware platforms, or is it subject to the same problems as System.Single and System.Double?

If System.Decimal is consistent, is there a free library that implements transcendental functions for it (cos, sin, tan, sqrt, log, etc.)?

+4
source share
1 answer

It is agreed that it will give the same results in all .NET implementations.

Agreed so that it always represents the correct result of operation no. Any floating point will have problems of some value. System.Decimal can only accurately represent numbers that will be exactly represented as decimal values. 1/3 will be displayed inaccurately as 0.333333 ... and many results of cos, sin, tan, sqrt and log will be approximations due to the fact that for any number system (for example, decimal or binary) there are a lot of values, which can only be presented in the closest approximation.

The C # specification says: 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. 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.

+2
source

All Articles