Java中,如何对大数开根号啊!

来源:百度知道 编辑:UC知道 时间:2024/06/30 23:36:17
在Java中,有没有对一个BigInteger,BigDecimal数开根号的函数,如果有,函数是什么?如果没有,怎么处理这个问题?
解决后,追加分!
假如开根号是一个无限小数,要怎样保存自己想要的n位呢?
例如sqrt(3),我想保存1000位,怎么搞啊?
我这里要求的是要求出小数点后多位(几百,几千甚至几万),如果是一般的话,直接用Math.sqrt(3)求就可以了!

java中对于大数BigInteger,BigDecimal开根号没有提供函数,可以参考以下实现方法:

import java.math.BigDecimal;
import java.math.BigInteger;
public class BigSquareRoot {
final static BigInteger HUNDRED = BigInteger.valueOf(100);

public static BigDecimal sqrt(BigDecimal number, int scale, int roundingMode) {
if (number.compareTo(BigDecimal.ZERO) < 0)
throw new ArithmeticException("sqrt with negative");
BigInteger integer = number.toBigInteger();
StringBuffer sb = new StringBuffer();
String strInt = integer.toString();
int lenInt = strInt.length();
if (lenInt % 2 != 0) {
strInt = '0' + strInt;
lenInt++;
}
BigInteger res = BigInteger.ZERO;
BigInteger rem = BigInteger.ZERO;
for (int i = 0; i < lenInt / 2; i++) {
res = res.multiply(BigInteger.TEN);
rem = rem.multiply(HUNDRED);

BigInteger temp = new BigInteger(strInt.substring(i * 2, i * 2 + 2));
rem = rem.add(temp);