Performing Math operations on decimal datatype in C#?

前端 未结 5 1112
情深已故
情深已故 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:07

    I don't understand why all the answers to that question are the same.

    There are several ways to calculate the square root from a number. One of them was proposed by Isaac Newton. I'll only write one of the simplest implementations of this method. I use it to improve the accuracy of double's square root.

    // x - a number, from which we need to calculate the square root
    // epsilon - an accuracy of calculation of the root from our number.
    // The result of the calculations will differ from an actual value
    // of the root on less than epslion.
    public static decimal Sqrt(decimal x, decimal epsilon = 0.0M)
    {
        if (x < 0) throw new OverflowException("Cannot calculate square root from a negative number");
    
        decimal current = (decimal)Math.Sqrt((double)x), previous;
        do
        {
            previous = current;
            if (previous == 0.0M) return 0;
            current = (previous + x / previous) / 2;
        }
        while (Math.Abs(previous - current) > epsilon);
        return current;
    }
    

    About speed: in the worst case (epsilon = 0 and number is decimal.MaxValue) the loop repeats less than a three times.

    If you want to know more, read this (Hacker's Delight by Henry S. Warren, Jr.)

提交回复
热议问题