Java BigDecimal Square Root sqrt(BigDecimal original, int scale)

Here you can find the source of sqrt(BigDecimal original, int scale)

Description

sqrt

License

Apache License

Declaration

public static BigDecimal sqrt(BigDecimal original, int scale) 

Method Source Code

//package com.java2s;
/*//from  w w  w .j  a v a  2s. co  m
     
 Copyright 2015 HJOW
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
     
 */

import java.math.BigDecimal;

public class Main {

    public static BigDecimal sqrt(BigDecimal original, int scale) {
        BigDecimal temp = new BigDecimal(String.valueOf(original));

        BigDecimal results = new BigDecimal("1.0");
        results.setScale(scale + 2);

        int loops = 0;

        while (true) {
            if (loops >= 1) {
                temp = new BigDecimal(String.valueOf(results));
            }

            temp.setScale(scale + 2, BigDecimal.ROUND_FLOOR);
            results = original.divide(temp, scale + 2, BigDecimal.ROUND_FLOOR).add(temp)
                    .divide(new BigDecimal("2.0"), scale + 2, BigDecimal.ROUND_FLOOR);
            if (temp.equals(results))
                break;

            loops++;
        }

        return results.setScale(scale, BigDecimal.ROUND_HALF_UP);
    }
}

Related

  1. sqrt(BigDecimal number)
  2. sqrt(BigDecimal number, RoundingMode rounding)
  3. sqrt(BigDecimal randicand)
  4. sqrt(BigDecimal value)
  5. sqrt(BigDecimal value, int decimalPlaces)
  6. sqrt(BigDecimal value, MathContext mc)