[英]Can someone explain me this function that finds the square root of an BigInteger in Java?
So I need to sqrt a BigInteger in pre Java 9 and I found below function to do that.所以我需要在 Java 9 之前对 BigInteger 进行 sqrt ,并且我在 function 下方找到了这样做。 I do understand the code, but I don't really get why its there.
我确实理解代码,但我真的不明白为什么它在那里。 So I guess I don't really get the math behind it.
所以我想我并没有真正理解它背后的数学原理。 Like why is (n / 32 + 8) used.
就像为什么使用 (n / 32 + 8) 一样。 Why is mid calculated the way it is.
为什么 mid 是这样计算的。 etc.
等等
BigInteger a = BigInteger.ONE;
BigInteger b = n.shiftRight(5).add(BigInteger.valueOf(8));
while (b.compareTo(a) >= 0) {
BigInteger mid = a.add(b).shiftRight(1);
if (mid.multiply(mid).compareTo(n) > 0) {
b = mid.subtract(BigInteger.ONE);
} else {
a = mid.add(BigInteger.ONE);
}
}
return a.subtract(BigInteger.ONE);
}
EDIT: James Reinstate Monica Polk is correct , this is not the Babylonian Method but rather the Bisection method.编辑:詹姆斯恢复莫妮卡波尔克是正确的,这不是巴比伦方法,而是二分法。 I did not look at the code carefully enough before answering.
在回答之前我没有仔细看代码。 Please see his answer as it is more accurate than mine.
请看他的回答,因为它比我的更准确。
This looks to be the Babylonian Method for approximating square roots.这看起来是近似平方根的巴比伦方法。 (n/32 + 8) is just used as a "seed", as providing a sane starting value can provide a better approximation in fewer iterations than just picking any number.
(n/32 + 8) 只是用作“种子”,因为提供一个合理的起始值可以在更少的迭代中提供更好的近似值,而不是仅仅选择任何数字。
The algorithm is the bisection method applied to finding the zero of the polynomial x 2 - n = 0 .该算法是用于找到多项式x 2 - n = 0的零点的二分法。 Why is ( n / 32 + 8 ) used as a seed?
为什么将 ( n / 32 + 8 ) 用作种子? I have no idea as it is a rather poor approximation.
我不知道,因为它是一个相当差的近似值。 A much better approximation that is almost as cheap to compute is
n.shiftRight(n.bitLength()/2);
n.shiftRight(n.bitLength()/2);
更好的近似值几乎与计算一样便宜
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.