Performing Math operations on decimal datatype in C#?

前端 未结 5 1113
情深已故
情深已故 2020-11-30 07:27

I was wondering if the above was at all possible. For example:

Math.Sqrt(myVariableHere);

When looking at the overload, it requires a doub

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 08:22

    I just came across this question, and I'd suggest a different algorithm than the one SLenik proposed. This is based on the Babylonian Method.

    public static decimal Sqrt(decimal x, decimal? guess = null)
    {
        var ourGuess = guess.GetValueOrDefault(x / 2m);
        var result = x / ourGuess;
        var average = (ourGuess + result) / 2m;
    
        if (average == ourGuess) // This checks for the maximum precision possible with a decimal.
            return average;
        else
            return Sqrt(x, average);
    }
    

    It doesn't require using the existing Sqrt function, and thus avoids converting to double and back, with the accompanying loss of precision.

提交回复
热议问题