Java BigIntegerMath sqrt() 函数
Guava的BigIntegerMath类的 sqrt(BigInteger x, RoundingMode mode) 方法返回x的 平方根 ,并按照指定的四舍五入模式进行取舍。
语法
public static BigInteger sqrt(BigInteger x, RoundingMode mode)
参数。此方法需要以下参数。
- x : 要找到其平方根的BigInteger数字。
- mode : 用于计算平方根的四舍五入模式。
返回值。该方法返回x的 平方根 ,并以指定的四舍五入模式取整。
异常: 该方法会抛出以下异常。
- IllegalArgumentException: 如果x<0。
- ArithmeticException: 如果模式是RoundingMode.UNNECESSARY并且sqrt(x)不是一个整数。
Enum RoundingMode
枚举常数 | 描述 |
---|---|
CEILING | 四舍五入模式,朝向正无穷大。 |
DOWN | 向零舍入的舍入模式。 |
FLOOR | 四舍五入到负无穷大的模式。 |
HALF_DOWN | 向 “最近的邻居 “舍入的舍入模式,除非两个邻居的距离相等,在这种情况下向下舍入。 |
HALF_EVEN | 向 “最近的邻居 “舍入的舍入模式,除非两个邻居都是等距离,在这种情况下,向偶数邻居舍入。 |
HALF_UP | 向 “最近的邻居 “舍入的舍入模式,除非两个邻居都是等距离,在这种情况下,向上舍入。 |
UNNECESSARY | 四舍五入模式,断言请求的操作有一个精确的结果,因此不需要四舍五入。 |
UP | 舍入模式,从零开始舍入。 |
下面的例子说明了 BigIntegerMath.sqrt() 方法。
例1 :
// Java code to show implementation of
// sqrt(BigInteger x, RoundingMode mode) method
// of Guava's BigIntegerMath class
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
// Driver code
public static void main(String args[])
{
BigInteger x1 = BigInteger.valueOf(226);
// Using sqrt(BigInteger x, RoundingMode mode)
// method of Guava's BigIntegerMath class
// The RoundingMode HALF_EVEN rounds towards
// the nearest neighbor unless both neighbors
// are equidistant, in which case, round towards
// the even neighbor.
BigInteger ans1 = BigIntegerMath
.sqrt(x1,
RoundingMode.HALF_EVEN);
System.out.println("Square root of " + x1
+ "with HALF_EVEN rounding mode is: "
+ ans1);
BigInteger x2 = BigInteger.valueOf(154);
// Using sqrt(BigInteger x, RoundingMode mode)
// method of Guava's BigIntegerMath class
// The RoundingMode FLOOR rounds towards
// negative infinity.
BigInteger ans2 = BigIntegerMath
.sqrt(x2,
RoundingMode.FLOOR);
System.out.println("Square root of " + x2
+ "with FLOOR rounding mode is: "
+ ans2);
}
}
输出。
Square root of 226with HALF_EVEN rounding mode is: 15
Square root of 154with FLOOR rounding mode is: 12
例2 :
// Java code to show implementation of
// sqrt(BigInteger x, RoundingMode mode) method
// of Guava's BigIntegerMath class
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
// Driver code
public static void main(String args[])
{
try {
BigInteger x1 = BigInteger.valueOf(-65);
// Using sqrt(BigInteger x, RoundingMode mode)
// method of Guava's BigIntegerMath class
// The RoundingMode HALF_EVEN rounds towards
// the nearest neighbor unless both neighbors
// are equidistant, in which case, round towards
// the even neighbor.
BigInteger ans1 = BigIntegerMath
.sqrt(x1,
RoundingMode.HALF_EVEN);
// This should throw "IllegalArgumentException"
// as x1 < 0
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出。
Exception: java.lang.IllegalArgumentException: x (-65) must be >= 0
参考资料: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#sqrt-java.math.BigInteger-java.math.RoundingMode-