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
- java数值精确计算
- java的精确计算
- java精确计算
- java精确计算
- Java精确计算小数
- Java精确计算
- Java bigdemical精确计算
- java小数精确计算
- java/android 精确计算
- Java中的精确计算
- Java 小数精确计算问题
- java中的精确商务计算
- java 浮点数精确计算
- java计算时间差,精确到纳秒
- java中的数字精确计算
- Java精确计算:BigDecimal类
- Java笔记3:Java精确计算
- JAVA-精确计算时的陷阱
- 安卓 | 使用AsyncTask进行Socket编程
- 博为峰Java技术文章 ——JavaSE Swing 滑动组件JSliderⅢ
- Windows下vs2015编译Chromium[2017/04/01]
- Kali-WIFI攻防(一)----无线网络嗅探工具Kismet
- centos下的nginx安装
- Java精确计算
- Java中的输入输出(I/O)总结
- C++抽象编程——STL(4)——vector中的排序和其他存储方式
- Swing的MVC结构
- java.lang.NullPointerException: Attempt to read from field 'int android.support.v4.app.Fragment.mCon
- C. Commentator problem (模拟退火)
- Android网络编程之TCP/IP的Socket、ServerSocket模式
- 关于float的值与浮动失效问题
- 五个运动员各两个个判断,每人对一个,