Пример #1
0
        public BigDecimal Get(BigDecimal n)
        {
            if(n.CompareTo(ZERO) <= 0) {
                throw new System.ArgumentException();
            }

            BigDecimal initialGuess = GetInitialApproximation(n);
            BigDecimal lastGuess = ZERO;
            BigDecimal guess = new BigDecimal(initialGuess.ToString());

            int iterations = 0;
            bool more = true;
            while(more) {
                lastGuess = guess;
                guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP);
                guess = guess.add(lastGuess);
                guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP);
                error = n.subtract(guess.multiply(guess));
                if(++iterations >= maxIterations) {
                    more = false;
                } else if(lastGuess.Equals(guess)) {
                    more = error.abs().CompareTo(ONE) >= 0;
                }
            }
            return guess;
        }