Java精确计算

来源:互联网 发布:清华协和医学院 知乎 编辑:程序博客网 时间:2024/05/19 04:51

在java.math 的包中有3个class,在这我只举BigInteger的例子

BigDecimal 不可变的、任意精度的有符号十进制数。
BigInteger 不可变的任意精度的整数。
MathContext 该对象是封装上下文设置的不可变对象,它描述数字运算符的某些规则,例如由 BigDecimal 类实现的规则。

在平常我们计算的时候比如计算10+2直接定义变量赋值以后就开始计算了,整型的还好,浮点型就悲剧了,误差很大,某些领域是不允许损失精度的,如金融领域或者通信领域就不允许有误差,存钱、取钱居然操作之后和我们预期的结果相违背了700.02取了200之后居然变成了500了,那么就是不可接受的
因此就需要专门的处理这些数据
像10+2,就可以用一个对象来保存10在用另一个对象来保存2然后在调用对象的方法add(加法操作)即可得出计算值(在打印出来即10进制人类能够看懂的东西)

例子如下

package math;import java.math.BigInteger;public class BigIntegerTest {    private static BigInteger b1 = new BigInteger("12");    private static BigInteger b2 = new BigInteger("15");    private static BigInteger b3 = new BigInteger("3");    public static void isAdd() {//添加        BigInteger bigInteger = b1.add(b2);        System.out.println("12+15 add 加法:"+bigInteger.toString());    }    public static void isSubtract() {//减法        BigInteger bigInteger = b2.subtract(b1);        System.out.println("15-12 subtract 减法:"+bigInteger.toString());    }    public static void isDivide() {//除法        BigInteger b = b1.divide(b3);        System.out.println("12/3 divide 除法:"+b.toString());    }    public static void isMultiply() {//乘法        BigInteger b = b1.multiply(b2);        System.out.println("12*15 multiply 乘法:"+b.toString());    }    public static void isRemainder() {//取模        BigInteger b = b1.remainder(b2);        System.out.println("12 % 15 remainder 取模:"+b.toString());    }    public static void isOr() {//或        BigInteger b = b1.or(b2);        System.out.println("12 | 15 or 或:"+b);    }    public static void isAnd() {//与        BigInteger b = b1.and(b2);        System.out.println("12 & 15 and 与:"+b);    }    public static void isShiftLeft() {//向左移动        BigInteger b = b1.shiftLeft(2);        System.out.println("12 移位 2个    shiftLeft:"+b);    }    public static void main(String[] args) {        isAdd();        isSubtract();        isDivide();        isMultiply();        isRemainder();        isOr();        isAnd();        isShiftLeft();    }}

console
12+15 add 加法:27
15-12 subtract 减法:3
12/3 divide 除法:4
12*15 multiply 乘法:180
12 % 15 remainder 取模:12
12 | 15 or 或:15
12 & 15 and 与:12
12 移位 2个 shiftLeft:48

0 0