Java BigDecimal Square Root sqrtNewtonRaphson(BigDecimal c, BigDecimal xn, BigDecimal precision)

Here you can find the source of sqrtNewtonRaphson(BigDecimal c, BigDecimal xn, BigDecimal precision)

Description

Private utility method used to compute the square root of a BigDecimal.

License

Open Source License

Declaration

private static BigDecimal sqrtNewtonRaphson(BigDecimal c, BigDecimal xn, BigDecimal precision) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    private static final BigDecimal SQRT_DIG = new BigDecimal(150);

    /**/*w ww .j av  a2  s.  c o m*/
     * Private utility method used to compute the square root of a BigDecimal.
     * 
     * @author Luciano Culacciatti 
     * @url http://www.codeproject.com/Tips/257031/Implementing-SqrtRoot-in-BigDecimal
     */
    private static BigDecimal sqrtNewtonRaphson(BigDecimal c, BigDecimal xn, BigDecimal precision) {
        BigDecimal fx = xn.pow(2).add(c.negate());
        BigDecimal fpx = xn.multiply(new BigDecimal(2));
        BigDecimal xn1 = fx.divide(fpx, 2 * SQRT_DIG.intValue(), RoundingMode.HALF_DOWN);
        xn1 = xn.add(xn1.negate());
        BigDecimal currentSquare = xn1.pow(2);
        BigDecimal currentPrecision = currentSquare.subtract(c);
        currentPrecision = currentPrecision.abs();
        if (currentPrecision.compareTo(precision) <= -1) {
            return xn1;
        }
        return sqrtNewtonRaphson(c, xn1, precision);
    }
}

Related

  1. sqrt(BigDecimal value)
  2. sqrt(BigDecimal value, int decimalPlaces)
  3. sqrt(BigDecimal value, MathContext mc)
  4. sqrt(BigDecimal x)
  5. sqrt(final ArrayList data)
  6. sqrtProcedure(MathContext mc, int digits, BigDecimal numberToBeSquareRooted, BigDecimal iteration1, BigDecimal iteration2, BigDecimal temp1, BigDecimal temp2)