Are there libraries for Square Root over BigDecimal?
JScience v4.3.1 has a Real
class which seems to be the equivalent of BigDecimal
and that might help you. An example of usage:
// The Square Root of Two, to 30 digits
// According to "The Square Root of Two, to 5 million digits."
// Source: http://www.gutenberg.org/files/129/129.txt
System.out.println("1.41421356237309504880168872420");
// Using JScience with 50 digits precision
Real.setExactPrecision(50);
System.out.println(Real.valueOf(2).sqrt());
// Using default java implementation
System.out.println(Math.sqrt(2));
> 1.41421356237309504880168872420
> 1.414213562373095048801689
> 1.4142135623730951
Edit: Updated the code and the links to reflect the current version at the time (v4.3.1). Based on @ile an @Tomasz comments, thanks.
Precise Square Roots in Java
Check something like JScience it has a decimal class where you can set the number of digits and subsequently the required precision.
something like this is what you need.
Getting much higher precision with BigDecimal (or another class) in Java
Here is an explanation why what you are doing is not working.
Math.pow()
returns a double
. So your code is calculating the value using the precision provided by double, and then creating a BigDecimal
from that double. It's too late to set the precision on the big decimal since it only has the double as input.
So you can not use Math.pow()
for your purpose. Instead you need to find another library that does arbitrary precision calculations.
Refer to this question for more: Java's BigDecimal.power(BigDecimal exponent): Is there a Java library that does it?
Get nth digit of a sqrt: getting digits that exceed the double scope
the "2" in the big decimal constructor is the value of what operation you want to do, the 1000 in the MathContext is how many digits you want to get from it.
so like this is how I would get get sqrt(2) to 1000 decimal places
public static void main(String[] args) {
BigDecimal digits = new BigDecimal("2");
BigDecimal num = digits.sqrt(new MathContext(1000));
System.out.println(num.toString());
}
Related Topics
Platform Independent Paths in Java
Best Way to Encode Text Data for Xml in Java
Java Ioexception "Too Many Open Files"
Convert Escaped Unicode Character Back to Actual Character
Read Whole Text Files from a Compression in Spark
How to Convert a String to Double in Java Using a Specific Locale
Randomly Select an Item from a List
Spring Boot 2.0.X Disable Security for Certain Profile
Testing Private Method Using Mockito
How to Merge Two PDF Files into One in Java
How to Make Java Honor the Dns Caching Timeout
How to Call Oracle Stored Procedure Which Include User-Defined Type in Java