JAVA的浮点运算精度问题和math类

JAVA的浮点运算精度问题和math类

問題的提出:
如果我們編譯運行下面這個程式會看到什麼?
public class Test{
public static void main(String args[]){
System.out.println(0.05+0.01);
System.out.println(1.0-0.42);
System.out.println(4.015*100);
System.out.println(123.3/100);
}
};
你沒有看錯!結果確實是
0.060000000000000005
0.5800000000000001
401.49999999999994
1.2329999999999999
Java中的簡單浮點數類型float和double不能夠進行運算。不光是Java,在其他很多編程語言中也有這樣的問題。在大多數情況下,計算的結果是準確的,但是多試幾次(可以做一個迴圈)就可以試出類似上面的錯誤。現在終於理解為什麼要有BCD碼了。
這個問題相當嚴重,如果你有9.999999999999元,你的電腦是不會認為你可以購買10元的商品的。
在有的編程語言中提供了專門的貨幣類型來處理這種情況,但是Java沒有。現在讓我們看看如何解決這個問題。


四捨五入
我們的第一個反應是做四捨五入。Math類中的round方法不能設置保留幾位小數,我們只能象這樣(保留兩位):
public double round(double value){
return Math.round(value*100)/100.0;
}
非常不幸,上面的代碼並不能正常工作,給這個方法傳入4.015它將返回4.01而不是4.02,如我們在上面看到的
4.015*100=401.49999999999994
因此如果我們要做到精確的四捨五入,不能利用簡單類型做任何運算
java.text.DecimalFormat也不能解決這個問題:
System.out.println(new java.text.DecimalFormat("0.00").format(4.025));
輸出是4.02
BigDecimal
在《Effective java》這本書中也提到這個原則,float和double只能用來做科學計算或者是工程計算,在商業計算中我們要用 java.math.BigDecimal。BigDecimal一共有4個夠造方法,我們不關心用BigInteger來夠造的那兩個,那麼還有兩個, 它們是:
BigDecimal(double val)
Translates a double into a BigDecimal.
BigDecimal(String val)
Translates the String repre sentation of a BigDecimal into a BigDecimal.
上面的API簡要描述相當的明確,而且通常情況下,上面的那一個使用起來要方便一些。我們可能想都不想就用上了,會有什麼問題呢?等到出了問題的時候,才發現上面哪個夠造方法的詳細說明中有這麼一段:
Note: the results of this constructor can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances nonwithstanding.
The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.

原來我們如果需要精確計算,非要用String來夠造BigDecimal不可!在《Effective java》一書中的例子是用String來夠造BigDecimal的,但是書上卻沒有強調這一點,這也許是一個小小的失誤吧。
解決方案
現在我們已經可以解決這個問題了,原則是使用BigDecimal並且一定要用String來夠造。
但是想像一下吧,如果我們要做一個加法運算,需要先將兩個浮點數轉為String,然後夠造成BigDecimal,在其中一個上調用add方法,傳入另 一個作為參數,然後把運算的結果(BigDecimal)再轉換為浮點數。你能夠忍受這麼煩瑣的過程嗎?下面我們提供一個工具類Arith來簡化操作。它 提供以下靜態方法,包括加減乘除和四捨五入:
public static double add(double v1,double v2)
public static double sub(double v1,double v2)
public static double mul(double v1,double v2)
public static double div(double v1,double v2)
public static double div(double v1,double v2,int scale)
public static double round(double v,int scale)

附錄

原始檔案Arith.java:
import java.math.BigDecimal;

/**
* 由於Java的簡單類型不能夠精確的對浮點數進行運算,這個工具類提供精
* 確的浮點數運算,包括加減乘除和四捨五入。
*/
public class Arith{

//默認除法運算精度
private static final int DEF_DIV_SCALE = 10;

//這個類不能實例化
private Arith(){
}


/**
* 提供精確的加法運算。
* @param v1 被加數
* @param v2 加數
* @return 兩個參數的和
*/
public static double add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}

/**
* 提供精確的減法運算。
* @param v1 被減數
* @param v2 減數
* @return 兩個參數的差
*/
public static double sub(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}

/**
* 提供精確的乘法運算。
* @param v1 被乘數
* @param v2 乘數
* @return 兩個參數的積
*/
public static double mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}

/**
* 提供(相對)精確的除法運算,當發生除不盡的情況時,精確到
* 小數點以後10位元,以後的數字四捨五入。
* @param v1 被除數
* @param v2 除數
* @return 兩個參數的商
*/
public static double div(double v1,double v2){
return div(v1,v2,DEF_DIV_SCALE);
}

/**
* 提供(相對)精確的除法運算。當發生除不盡的情況時,由scale參數指
* 定精度,以後的數字四捨五入。
* @param v1 被除數
* @param v2 除數
* @param scale 表示表示需要精確到小數點以後幾位。
* @return 兩個參數的商
*/
public static double div(double v1,double v2,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}

/**
* 提供精確的小數位四捨五入處理。
* @param v 需要四捨五入的數位
* @param scale 小數點後保留幾位
* @return 四捨五入後的結果
*/
public static double round(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
};

==================================================

1.舍掉小数取整:Math.floor(3.5)=3

2.四舍五入取整:Math.rint(3.5)=4

3.进位取整:Math.ceil(3.1)=4


在Java中进行取整,尤其是四舍五入取整还有点麻烦。

下面是我根据网上的一些解答整理的三种取整运算(包括截尾取整,四舍五入,凑整),类似于面向过程语言(如C和Basic)中的取整函数(不过在Java中它叫类的方法,“类名.方法名(参数)”的运算都是类的静态方法)。

其中,注释掉的那段是在网上查到的有的朋友认为正确的四舍五入的取整方法,但是经过我的实验却是不正确的四舍五入的取整方法。

TestGetInt.java 源代码


import java.math.BigDecimal;
import java.text.DecimalFormat;

public class TestGetInt{
   public static void main(String[] args){
     double i=2, j=2.1, k=2.5, m=2.9;
     System.out.println("舍掉小数取整:Math.floor(2)=" + (int)Math.floor(i));
     System.out.println("舍掉小数取整:Math.floor(2.1)=" + (int)Math.floor(j));
     System.out.println("舍掉小数取整:Math.floor(2.5)=" + (int)Math.floor(k));
     System.out.println("舍掉小数取整:Math.floor(2.9)=" + (int)Math.floor(m));
                                                                               
     /* 这段被注释的代码不能正确的实现四舍五入取整
     System.out.println("四舍五入取整:Math.rint(2)=" + (int)Math.rint(i));
     System.out.println("四舍五入取整:Math.rint(2.1)=" + (int)Math.rint(j));
     System.out.println("四舍五入取整:Math.rint(2.5)=" + (int)Math.rint(k));
     System.out.println("四舍五入取整:Math.rint(2.9)=" + (int)Math.rint(m));
    
     System.out.println("四舍五入取整:(2)=" + new DecimalFormat("0").format(i));
     System.out.println("四舍五入取整:(2.1)=" + new DecimalFormat("0").format(i));
     System.out.println("四舍五入取整:(2.5)=" + new DecimalFormat("0").format(i));
     System.out.println("四舍五入取整:(2.9)=" + new DecimalFormat("0").format(i));
     */
    
     System.out.println("四舍五入取整:(2)=" + new BigDecimal("2").setScale(0, BigDecimal.ROUND_HALF_UP));
     System.out.println("四舍五入取整:(2.1)=" + new BigDecimal("2.1").setScale(0, BigDecimal.ROUND_HALF_UP));
     System.out.println("四舍五入取整:(2.5)=" + new BigDecimal("2.5").setScale(0, BigDecimal.ROUND_HALF_UP));
     System.out.println("四舍五入取整:(2.9)=" + new BigDecimal("2.9").setScale(0, BigDecimal.ROUND_HALF_UP));

     System.out.println("凑整:Math.ceil(2)=" + (int)Math.ceil(i));
     System.out.println("凑整:Math.ceil(2.1)=" + (int)Math.ceil(j));
     System.out.println("凑整:Math.ceil(2.5)=" + (int)Math.ceil(k));
     System.out.println("凑整:Math.ceil(2.9)=" + (int)Math.ceil(m));

     System.out.println("舍掉小数取整:Math.floor(-2)=" + (int)Math.floor(-i));
     System.out.println("舍掉小数取整:Math.floor(-2.1)=" + (int)Math.floor(-j));
     System.out.println("舍掉小数取整:Math.floor(-2.5)=" + (int)Math.floor(-k));
     System.out.println("舍掉小数取整:Math.floor(-2.9)=" + (int)Math.floor(-m));
    
     System.out.println("四舍五入取整:(-2)=" + new BigDecimal("-2").setScale(0, BigDecimal.ROUND_HALF_UP));
     System.out.println("四舍五入取整:(-2.1)=" + new BigDecimal("-2.1").setScale(0, BigDecimal.ROUND_HALF_UP));
     System.out.println("四舍五入取整:(-2.5)=" + new BigDecimal("-2.5").setScale(0, BigDecimal.ROUND_HALF_UP));
     System.out.println("四舍五入取整:(-2.9)=" + new BigDecimal("-2.9").setScale(0, BigDecimal.ROUND_HALF_UP));

     System.out.println("凑整:Math.ceil(-2)=" + (int)Math.ceil(-i));
     System.out.println("凑整:Math.ceil(-2.1)=" + (int)Math.ceil(-j));
     System.out.println("凑整:Math.ceil(-2.5)=" + (int)Math.ceil(-k));
     System.out.println("凑整:Math.ceil(-2.9)=" + (int)Math.ceil(-m));
     }
}

=====================================================

数学类

算法,特别是数值算法,按使用习惯是不应该封装成为类的。就仿佛C++的算法模板库,使用起来很方便,但java已经被设计成为纯面向对象的语言了,所以 java采用了静态函数来完成Math类。Math类非常丰富而且简便,封装了几乎所有数学上需要的基本运算,是一个非常出色的类组件。
这也就是很多C++程序员羡慕java程序员的原因——java程序员有太多丰富的组件可以调用,几乎不用自己费神去实现那些复杂而且无聊的东西。
下面介绍部分Math的方法(我觉得我能用到的)。

Math.PI 记录的圆周率
Math.E&nbsp;记录e的常量
Math中还有一些类似的常量,都是一些工程数学常用量。

Math.abs 求绝对值
Math.sin 正弦函数&nbsp;Math.asin 反正弦函数
Math.cos 余弦函数&nbsp;Math.acos 反余弦函数
Math.tan 正切函数&nbsp;Math.atan 反正切函数&nbsp;Math.atan2 商的反正切函数
Math.toDegrees 弧度转化为角度&nbsp;Math.toRadians 角度转化为弧度
Math.ceil 得到不小于某数的最大整数
Math.floor 得到不大于某数的最大整数
Math.IEEEremainder 求余
Math.max 求两数中最大
Math.min 求两数中最小
Math.sqrt 求开方
Math.pow 求某数的任意次方, 抛出ArithmeticException处理溢出异常
Math.exp 求e的任意次方
Math.log10 以10为底的对数
Math.log 自然对数
Math.rint 求距离某数最近的整数(可能比某数大,也可能比它小)
Math.round 同上,返回int型或者long型(上一个函数返回double型)
Math.random 返回0,1之间的一个随机数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值