版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34231010/article/details/83957439
目录
【数学运算】
Guava 对于数学运算进行了专门的封装,对运算溢出、性能以及可读性等方面做了精心的设计。来看看吧:
Guava Math主要处理三种整数类型:int、long和BigInteger。这三种类型的运算工具类分别叫做IntMath、LongMath和BigIntegerMath。
一、整数运算
有溢出的检查运算:当运算结果溢出时,会抛出运算失败异常而不是忽略溢出。
int方法 | long方法 |
---|---|
IntMath.checkedAdd | LongMath.checkedAdd |
IntMath.checkedSubtract | LongMath.checkedSubtract |
IntMath.checkedMultiply | LongMath.checkedMultiply |
IntMath.checkedPow | LongMath.checkedPow |
二、实数运算
在进行实数运算上,guava专门在性能上有所优化,运算过程采用整数或位运算,使得执行效率更高(除平方根运算)。
运算 | IntMath | LongMath | BigIntegerMath |
---|---|---|---|
除法 | divide(int, int, RoundingMode) | divide(long, long, RoundingMode) | divide(BigInteger, BigInteger, RoundingMode) |
2为底的对数 | log2(int, RoundingMode) | log2(long, RoundingMode) | log2(BigInteger, RoundingMode) |
10为底的对数 | log10(int, RoundingMode) | log10(long, RoundingMode) | log10(BigInteger, RoundingMode) |
平方根 | sqrt(int, RoundingMode) | sqrt(long, RoundingMode) | sqrt(BigInteger, RoundingMode) |
补充:RoundingMode 为java.math 包下的枚举类,用于表示取舍模式
枚举 | 说明 |
---|---|
DOWN | 向零方向舍入(去尾法) |
UP | 远离零方向舍入 |
FLOOR | 向负无限大方向舍入 |
CEILING | 向正无限大方向舍入 |
UNNECESSARY | 不需要舍入,如果用此模式进行舍入,应直接抛出ArithmeticException |
HALF_UP | 向最近的整数舍入,其中x.5远离零方向舍入 |
HALF_DOWN | 向最近的整数舍入,其中x.5向零方向舍入 |
HALF_EVEN | 向最近的整数舍入,其中x.5向相邻的偶数舍入 |
三、附加功能
此外,还有一些常用的数学运算函数。
运算 | IntMath | LongMath | BigIntegerMath |
---|---|---|---|
最大公约数 | gcd(int, int) | gcd(long, long) | BigInteger.gcd(BigInteger) |
取模 | mod(int, int) | mod(long, long) | BigInteger.mod(BigInteger) |
取幂 | pow(int, int) | pow(long, int) | BigInteger.pow(int) |
是否2的幂 | isPowerOfTwo(int) | isPowerOfTwo(long) | isPowerOfTwo(BigInteger) |
阶乘 | factorial(int) | factorial(int) | factorial(int) |
二项式系数 | binomial(int, int) | binomial(int, int) | binomial(int, int) |
下面是Guava Math 实现 整数幂运算 的方法,通过位运算实现:
public static int pow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
return (k < Integer.SIZE) ? (1 << k) : 0;
case (-2):
if (k < Integer.SIZE) {
return ((k & 1) == 0) ? (1 << k) : -(1 << k);
} else {
return 0;
}
default:
// continue below to handle the general case
}
for (int accum = 1;; k >>= 1) {
switch (k) {
case 0:
return accum;
case 1:
return b * accum;
default:
accum *= ((k & 1) == 0) ? 1 : b;
b *= b;
}
}
}
四、浮点数运算
JDK比较彻底地涵盖了浮点数运算,但Guava在DoubleMath类中也提供了一些有用的方法。
Method | 说明 |
---|---|
isMathematicalInteger(double) | 判断该浮点数是不是一个整数 |
roundToInt(double, RoundingMode) | 舍入为int;对无限小数、溢出抛出异常 |
roundToLong(double, RoundingMode) | 舍入为long;对无限小数、溢出抛出异常 |
roundToBigInteger(double, RoundingMode) | 舍入为BigInteger;对无限小数抛出异常 |
log2(double, RoundingMode) | 2的浮点对数,并且舍入为int,比JDK的Math.log(double) 更快 |