简体   繁体   中英

How can i get precision up-to 128 decimal places in C#?

I have tried BigInteger, decimal, float and long but no luck. Screenshot of required output example

It is a fairly easy task to write your own rational class; remember, rationals are just pairs of integers, and you already have BigInteger.

In this series of articles I show how to devise your own big integer and big rational classes starting from absolutely nothing, not even integers . Note that this is not fast and not intended to be fast; it is intended to be educational. You can use the techniques I describe in this series to help you when designing your arithmetic class.

https://ericlippert.com/2013/09/16/math-from-scratch-part-one/

Or, if you don't want to write it yourself, you can always use the one from Microsoft:

http://bcl.codeplex.com/wikipage?title=BigRational&referringTitle=Home

But that said...

I need a minimum of 128 decimal places to calculate precise probabilities of events between different time steps

Do you need 128 decimal places to represent 128 digits of precision , or of magnitude ? Because if it is just magnitude, then simply do a transformation of your probability math into logarithms and do the math in doubles.

The easiest way to achieve arbitrary precision numbers is to combine the BigInteger class from System.Numerics with an int exponent. You could use BigInteger for your exponent, but this is likely overkill as the numbers would be well beyong meaningful in scale.

So if you create a class along these lines:

public class ArbDecimal
{
    BigInteger value;
    int exponent;
    public override string ToString()
    {
         StringBuilder sb = new StringBuilder();
         int place;
         foreach (char digit in value.ToString())
         {
             if (place++ == value.ToString().Length - exponent)
             {
                 sb.Append('.');
             }
             sb.Append(digit);
         }
         return sb.ToString();
    }
}

You should then be able to define your mathematical operations using the laws of indices with the value and exponent fields.

For instance, to achieve addition, you would scale the larger value to have the same exponent as the smaller one by multiplying it by 10^(largerExp-smallerExp) then adding the two values and rescaling.


In your class, the number 0.01 would be represented like:

value = 1

exponent = -2

Due to the fact that 1*10^-2 = 0.01 .


Utilising this method, you can store arbitrarily precise (and large) numbers limited only by the available ram and the .NET framework's object size limit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM