Created
March 30, 2015 15:03
-
-
Save flightonary/404a94791594d7f568f1 to your computer and use it in GitHub Desktop.
BigDecimal Sqrt in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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