Compute the square root of x to a given scale, x >= 0. - Java java.lang

Java examples for java.lang:Math Operation

Description

Compute the square root of x to a given scale, x >= 0.

Demo Code

/*/*from   w  w w. ja  va2  s.  c  om*/
 Anders H?fft, note: This class was downloaded as a quick, and temprory, way of getting a BigDecimal ln() method. 
 The code belongs to Cyclos. See comment below:

 This file is part of Cyclos (www.cyclos.org).
 A project of the Social Trade Organisation (www.socialtrade.org).
 Cyclos is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.
 Cyclos is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.
 You should have received a copy of the GNU General Public License
 along with Cyclos; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
//package com.java2s;
import java.math.BigDecimal;
import java.math.BigInteger;

public class Main {
    public static void main(String[] argv) throws Exception {
        BigDecimal x = new BigDecimal("1234");
        int scale = 2;
        System.out.println(sqrt(x, scale));
    }

    /**
     * Compute the square root of x to a given scale, x >= 0. Use Newton's algorithm.
     * @param x the value of x
     * @param scale the desired scale of the result
     * @return the result value
     */
    public static BigDecimal sqrt(final BigDecimal x, final int scale) {
        // Check that x >= 0.
        if (x.signum() < 0) {
            throw new IllegalArgumentException("x < 0");
        }

        // n = x*(10^(2*scale))
        final BigInteger n = x.movePointRight(scale << 1).toBigInteger();

        // The first approximation is the upper half of n.
        final int bits = (n.bitLength() + 1) >> 1;
        BigInteger ix = n.shiftRight(bits);
        BigInteger ixPrev;

        // Loop until the approximations converge
        // (two successive approximations are equal after rounding).
        do {
            ixPrev = ix;

            // x = (x + n/x)/2
            ix = ix.add(n.divide(ix)).shiftRight(1);

            Thread.yield();
        } while (ix.compareTo(ixPrev) != 0);

        return new BigDecimal(ix, scale);
    }
}

Related Tutorials