场景

Java核心工具库Guava介绍以及Optional和Preconditions使用进行非空和数据校验:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/127683387

为什么使用 Guava Math

1、Guava Math 针对各种不常见的溢出情况都有充分的测试;对溢出语义,Guava 文档也有相应的说明;

如果运算的溢出检查不能通过,将导致快速失败;

2、Guava Math 的性能经过了精心的设计和调优;虽然性能不可避免地依据具体硬件细节而有所差异

,但 Guava Math 的速度通常可以与 Apache Commons 的 MathUtils 相比,在某些场景下甚至还有显著提升;

3、Guava Math 在设计上考虑了可读性和正确的编程习惯;IntMath.log2(x, CEILING) 所表达的含义,

即使在快速阅读时也是清晰明确的。而 32-Integer.numberOfLeadingZeros(x – 1)对于阅读者来说则不够清晰。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

有溢出检查的运算

Guava Math 提供了若干有溢出检查的运算方法:结果溢出时,这些方法将快速失败而不是忽略溢出。

        System.out.println(IntMath.checkedAdd(1000,2500));//3500
        System.out.println(IntMath.checkedSubtract(10000,2500));//7500
        System.out.println(IntMath.checkedMultiply(1000,250));//250000
        //checkedPow(int b, int k) 计算b的k次方
        System.out.println(IntMath.checkedPow(2,5));//32

        //System.out.println(IntMath.checkedPow(Integer.MAX_VALUE,Integer.MAX_VALUE));//java.lang.ArithmeticException: overflow: checkedPow

 

 

实数运算

IntMath、LongMath 和 BigIntegerMath 提供了很多实数运算的方法,并把最终运算结果舍入成整数。

这些方法接受一个java.math.RoundingMode枚举值作为舍入的模式

        •DOWN:向零方向舍入(去尾法)
        •UP:远离零方向舍入
        •FLOOR:向负无限大方向舍入
        •CEILING:向正无限大方向舍入
        •UNNECESSARY:不需要舍入,如果用此模式进行舍入,应直接抛出 ArithmeticException
        •HALF_UP:向最近的整数舍入,其中 x.5 远离零方向舍入
        •HALF_DOWN:向最近的整数舍入,其中 x.5 向零方向舍入
        •HALF_EVEN:向最近的整数舍入,其中 x.5 向相邻的偶数舍入

        //divide除法
        System.out.println(IntMath.divide(19,4,RoundingMode.FLOOR));//4
        //sqrt 平方根
        System.out.println(IntMath.sqrt(4,RoundingMode.CEILING));//2
        System.out.println(IntMath.sqrt(5,RoundingMode.CEILING));//3
        //log2 以2为底的对数
        System.out.println(IntMath.log2(6,RoundingMode.FLOOR));//2
        //log10 以10为底的对数
        System.out.println(IntMath.log10(10,RoundingMode.FLOOR));//1

Guava 还另外提供了一些有用的运算函数

        //gcd 最大公约数
        System.out.println(IntMath.gcd(6,9));//3
        //mod 取模
        System.out.println(IntMath.mod(10,2));//0
        //pow 取幂
        System.out.println(IntMath.pow(2,6));//64
        //isPowerOfTwo是否2的幂
        System.out.println(IntMath.isPowerOfTwo(4));//true
        System.out.println(IntMath.isPowerOfTwo(5));//false
        //factorial 阶乘
        System.out.println(IntMath.factorial(3));//6
        //binomial 二项式系数
        System.out.println(IntMath.binomial(4,2));//6

 

 

原文地址:http://www.cnblogs.com/badaoliumangqizhi/p/16919458.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性