如果基本的整数和浮点数精度不足以满足需求,那么可以使用 java.math 包中两个很有用的类 : BigInteger和 BigDecimal。这两个类可以处理包含任意长度数字序列的数值。BigInteger类实现任意精度的整数运算,BiqDecimal 实现任意精度的浮点数运算。
使用静态的 valueOf 方法可以将一个普通的数转换为大数:
BigInteger a = BigInteger.valueOf(100);
【资料图】
对于更大的数,可以使用一个带字符串参数的构造器:
BigInteger reallyBig = new BigInteger("222232244629420445529739893461909967206666939096499764990979600") ;
另外还有一些常量: BigInteger.ZER0、BigInteger.ONE 和 BigInteger.TEN,Java 9之后还增加了BigInteger.TWO。
警告: 对于BigDecimal 类,总是应当使用带一个字符串参数的构造器。还有一个BigDecimal(double)构造器,不过这个构造器本质上很容易产生舍入误差,例如,newBigDecimal(0.1)会得到以下数位:
01000000000000000055511151231257827021181583404541015625
遗憾的是,不能使用人们熟悉的算术运算符(+ - * /)来组合大数,而需要使用大数类中的 add 和 multiply 等方法。
BigInteger c = a.add(b); // c= a + b;
BigInteger d = c.multiply (b.add(BigInteger.valueOf(2))) ; // d = c * ( b + 2)
C++ 注释 : 与 C++ 不同,Java 不能通过编程实现运算符重载。使用 BigInteger 类的程序员无法重定义 + 和 * 运算符来提供 BigInteger 类的 add和 multiply 运算。Java语言的设计者重载了 + 运算符来完成字符串的拼接,但没有重载其他的运算符,也没有给Java 程序员提供机会在他们自己的类中重载运算符。
程序清单 3-6 是对程序清单 3-5 中彩概率程序的改进,更新为使用大数。例如,假设你
被邀请参加抽奖活动,并从 490 个可能的数中抽取 60 个,这个程序会告诉你中彩的概率是
1/716395843461995557415116222540092933411717612789263493493351013459481104668848。祝你好运!
在程序清单3 - 5 中,会计算一下语句
lotteryOdds = lotteryOdds * ( n - i + 1) ;
如果对 lotteryOdds 和 n 使用大数,则相应语句为
lotteryOdds = lotteryOdds . multiply ( n.subtract ( BigInteger.valueOf(i -1)).divide(BigInteger.valueOf(i)) ;
程序清单 3 -6 BigIntegerTest.java
BigInteger API
java.math.BigInteger
BigInteger add(BigInteger other) // 加
BigInteger subtract(BigInteger other) // 减
BigInteger multiply(BigInteger other) // 乘
BigInteger divide(BigInteger other) // 除
BigInteger mod(BigInteger other) // 模
BigInteger sqrt() // 平方根 . since JDK 9
int compareTo(BigInteger other) // 相等则返回0 , > other 则返回正数,< other 返回负数
static BigInteger valueOf(long x) 返回等于x的大数
java.math.BigDecimal
BigDecimal (String digits) // 用给定数构造一个大数实例
BigDecimal add(BigDecimal other)
BigDecimal subtract(BigDecimal other)
BigDecimal multiply(BigDecimal other)
BigDecimal divide(BigDecimal other) 如果商是一个无限小数,则会抛出异常
BigDecimal divide(BigDecimal other , RoundingMode mode) since jdk5. 如果商是一个无限小数,使用 mode 来指定舍入方式,比如四舍五入。
int compareTo(BigDecimal other) 相等则返回0 , > other 则返回正数,< other 返回负数