Can C# store more precise data than doubles?

2019-01-20 08:47发布

问题:

double in C# don't hold enough precision for my needs. I am writing a fractal program, and after zooming in a few times I run out of precision.

I there a data type that can hold more precise floating-point information (i.e more decimal places) than a double?

回答1:

Yes, decimal is designed for just that.

However, do be aware that the range of the decimal type is smaller than a double. That is double can hold a larger value, but it does so by losing precision. Or, as stated on MSDN:

The decimal keyword denotes a 128-bit data type. Compared to floating-point types, the decimal type has a greater precision and a smaller range, which makes it suitable for financial and monetary calculations. The approximate range and precision for the decimal type are shown in the following table.

The primary difference between decimal and double is that decimal is fixed-point and double is floating point. That means that decimal stores an exact value, while double represents a value represented by a fraction, and is less precise. A decimalis 128 bits, so it takes the double space to store. Calculations on decimal is also slower (measure !).

If you need even larger precision, then BigInteger can be used from .NET 4. (You will need to handle decimal points yourself). Here you should be aware, that BigInteger is immutable, so any arithmetic operation on it will create a new instance - if numbers are large, this might be crippling for performance.

I suggest you look into exactly how precise you need to be. Perhaps your algorithm can work with normalized values, that can be smaller ? If performance is an issue, one of the built in floating point types are likely to be faster.



回答2:

The .NET Framework 4 introduces the System.Numerics.BigInteger struct that can hold numbers with an arbitrary large precision.



回答3:

Check out BigInteger (.NET 4) if you need even more precision than Decimal gives you.