Can we compute the square root of a BigDecimal
in Java by using only the Java API and not a custom-made 100-line algorithm?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
If you want to calculate square roots for numbers with more digits than fit in a double (a BigDecimal with a large scale) :
Wikipedia has an article for computing square roots: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
This is my implementation of it:
setScale(scale + 3, RoundingMode.Floor)
because over calculating gives more accuracy.RoundingMode.Floor
truncates the number,RoundingMode.HALF_UP
does normal rounding.This work perfect! Very fast for more than 65536 digits!
If you need to find only integer square roots - these are two methods that can be used.
Newton's method - very fast even for 1000 digits BigInteger:
Bisection method - is up to 50x times slower than Newton's - use only in educational purpose:
Here is very accurate and fast solution, it's based on my BigIntSqRoot solution and the next observation: The square root of A^2B - Is A multiply the root of B. Using this method I can easily calculate the first 1000 digits of square root of 2.
So here is the source code