Guava BigIntegerMath类的方法sqrt(BigInteger x,RoundingMode模式)返回x的平方根,并以指定的舍入模式进行四舍五入。
用法:
public static BigInteger sqrt(BigInteger x, RoundingMode mode)
参数:此方法采用以下参数:
x:要找到其平方根的BigInteger编号。
mode:用于计算平方根的舍入模式。
返回值:此方法返回x的平方根,并使用指定的舍入模式进行舍入。
异常:此方法引发以下异常:
IllegalArgumentException:如果x <0。
ArithmeticException:如果mode为RoundingMode.UNNECESSARY且sqrt(x)不是整数。
Enum RoundingMode
枚举常量
描述
CEILING
舍入模式向正无穷大舍入。
DOWN
舍入模式向零舍入。
FLOOR
舍入模式向负无穷大舍入。
HALF_DOWN
除非两个邻居等距,否则舍入模式将朝“nearest neighbor”舍入。
HALF_EVEN
舍入模式向“nearest neighbor”舍入,除非两个邻居都等距,在这种情况下,向偶数邻居舍入。
HALF_UP
除非两个邻居等距,否则舍入模式将朝“nearest neighbor”舍入。
UNNECESSARY
舍入模式可以断言所请求的操作具有准确的结果,因此不需要舍入。
UP
舍入模式从零舍入。
以下示例说明了BifIntegerMath.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