Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've used this and it works quite well. <a href="http://en.wikipedia.org/wiki/Newton&#39;s_method#Examples">Here's an example of how the algorithm works at a high level.</a></p> <p>Edit: I was curious to see just how accurate this was as defined below. Here is the sqrt(2) from an <a href="http://apod.nasa.gov/htmltest/gifcity/sqrt2.1mil">official source</a>:</p> <pre><code>(first 200 digits) 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147 </code></pre> <p>and here it is using the approach I outline below with <code>SQRT_DIG</code> equal to 150:</p> <pre><code>(first 200 digits) 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206086685 </code></pre> <p>The first deviation occurs after <strong>195 digits of precision</strong>. Use at your own risk if you need such a high level of precision as this.</p> <p>Changing <code>SQRT_DIG</code> to 1000 yielded <strong>1570 digits of precision</strong>.</p> <pre><code>private static final BigDecimal SQRT_DIG = new BigDecimal(150); private static final BigDecimal SQRT_PRE = new BigDecimal(10).pow(SQRT_DIG.intValue()); /** * 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) &lt;= -1){ return xn1; } return sqrtNewtonRaphson(c, xn1, precision); } /** * Uses Newton Raphson to compute the square root of a BigDecimal. * * @author Luciano Culacciatti * @url http://www.codeproject.com/Tips/257031/Implementing-SqrtRoot-in-BigDecimal */ public static BigDecimal bigSqrt(BigDecimal c){ return sqrtNewtonRaphson(c,new BigDecimal(1),new BigDecimal(1).divide(SQRT_PRE)); } </code></pre> <p>be sure to check out barwnikk's answer. it's more concise and seemingly offers as good or better precision.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload