Guava LongMath类
LongMath 是用来对Long值进行数学运算。基本的独立数学函数根据涉及的主要数字类型分为IntMath、LongMath、DoubleMath和BigIntegerMath类。这些类具有平行结构,但每个类只支持相关的函数子集。
声明 : com.google.common.math.LongMath类的声明是 :
@GwtCompatible(emulated = true) public final class LongMath extends Object
下表显示了Guava的LongMath类提供的一些方法。
异常 :
- log2 : 如果x<=0,则出现IllegalArgumentException
- log10 : 如果x<=0,则出现IllegalArgumentException
- pow : 如果k<0,则出现IllegalArgumentException
- sqrt : 如果x<0,则出现IllegalArgumentException
- divide : 如果q==0,或者mode==UNNECESSARY,且a不是b的整数倍,则出现ArithmeticException
- mod : 如果m<=0,则出现算术异常
- gcd : 如果a<0或b<0,则出现IllegalArgumentException
- checkedAdd: 如果a + b在有符号长算术中溢出,则出现算术异常
- checkedSubtract : 如果a – b在有符号长算术中溢出,则出现算术异常
- checkedMultiply : checkedPow : 如果a * b在有符号长算术中溢出,则出现算术异常
- checkedPow : 如果b的k次方在有符号长算术中溢出,则出现算术异常
- factorial : 如果n<0,则出现IllegalArgumentException
- binomial : 如果n<0,k<0或k>n
Guava的LongMath类提供的一些其他方法是。
例子1 :
// Java code to show implementation of // LongMath Class of Guava import java.math.RoundingMode; import com.google.common.math.LongMath; class GFG { // Driver code public static void main(String args[]) { // Creating an object of GFG class GFG obj = new GFG(); // Function calling obj.examples(); } private void examples() { try { // exception will be thrown as 80 is not // completely divisible by 3 // thus rounding is required, and // RoundingMode is set as UNNESSARY System.out.println(LongMath.divide(80, 3, RoundingMode.UNNECESSARY)); } catch (ArithmeticException ex) { System.out.println("Error Message is : " + ex.getMessage()); } } }
输出:
Error Message is : mode was UNNECESSARY, but rounding was necessary
例子2 :
// Java code to show implementation of // LongMath Class of Guava import java.math.RoundingMode; import com.google.common.math.LongMath; class GFG { // Driver code public static void main(String args[]) { // Creating an object of GFG class GFG obj = new GFG(); // Function calling obj.examples(); } private void examples() { // As 120 is divisible by 4, so // no exception is thrown System.out.println(LongMath.divide(120, 4, RoundingMode.UNNECESSARY)); // To compute GCD of two integers System.out.println("GCD is : " + LongMath.gcd(70, 14)); // To compute log to base 10 System.out.println("Log10 is : " + LongMath.log10(1000, RoundingMode.HALF_EVEN)); // To compute remainder System.out.println("modulus is : " + LongMath.mod(125, 5)); // To compute factorial System.out.println("factorial is : " + LongMath.factorial(7)); // To compute log to base 2 System.out.println("Log2 is : " + LongMath.log2(8, RoundingMode.HALF_EVEN)); // To compute square root System.out.println("sqrt is : " + LongMath.sqrt(LongMath.pow(12, 2), RoundingMode.HALF_EVEN)); } }
输出:
30 GCD is : 14 Log10 is : 3 modulus is : 0 factorial is : 5040 Log2 is : 3 sqrt is : 12
参考资料 :Google Guava
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com