Java examples for java.math:BigDecimal
BigDecimal the Babylonian square root method (Newton's method)
//package com.java2s; import java.math.BigDecimal; import static java.math.RoundingMode.HALF_UP; public class Main { public static void main(String[] argv) throws Exception { BigDecimal A = new BigDecimal("1234"); int SCALE = 2; System.out.println(sqrt(A, SCALE)); }//from w w w. j a va 2 s . c o m public static final BigDecimal TWO = BigDecimal.valueOf(2); /** * the Babylonian square root method (Newton's method) * * @param A * @param SCALE * @return */ public static BigDecimal sqrt(BigDecimal A, final int SCALE) { BigDecimal x0 = new BigDecimal("0"); BigDecimal x1 = new BigDecimal(Math.sqrt(A.doubleValue())); while (!x0.equals(x1)) { x0 = x1; x1 = A.divide(x0, SCALE, HALF_UP); x1 = x1.add(x0); x1 = x1.divide(TWO, SCALE, HALF_UP); } return x1; } }