Skip to content

Instantly share code, notes, and snippets.

@flightonary
Created March 30, 2015 15:03
Show Gist options
  • Save flightonary/404a94791594d7f568f1 to your computer and use it in GitHub Desktop.
Save flightonary/404a94791594d7f568f1 to your computer and use it in GitHub Desktop.
BigDecimal Sqrt in Scala
import java.math.BigDecimal
import java.math.MathContext
def sqrt(a: BigDecimal, scale: Int): BigDecimal = {
var x = new BigDecimal( Math.sqrt(a.doubleValue()), MathContext.DECIMAL64 )
if (scale < 17) {
return x
}
val b2 = new BigDecimal(2)
var tempScale = 16
while(tempScale < scale){
//x = x - (x * x - a) / (2 * x);
x = x.subtract(x.multiply(x).subtract(a).divide(x.multiply(b2), scale, BigDecimal.ROUND_HALF_EVEN))
tempScale *= 2
}
return x
}
System.out.println(sqrt(new BigDecimal(2), 50))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment