Java 中 float 或者double 類型比較大小的正確方式


一、基於閾值的比較

(1)設置一個精度e,

(2)兩數相減的結果取絕對值dif

(3)如果dif<e,兩數相等,否則不等

 1 private static void thresholdBasedFloatsComparison()
 2 {
 3     final double THRESHOLD = .0001;
 4  
 5     //Method 1
 6     double f1 = .0;
 7     for (int i = 1; i <= 11; i++) {
 8         f1 += .1;
 9     }
10  
11     //Method 2
12     double f2 = .1 * 11;
13  
14     System.out.println("f1 = " + f1);
15     System.out.println("f2 = " + f2);
16  
17     if (Math.abs(f1 - f2) < THRESHOLD)
18         System.out.println("f1 and f2 are equal using threshold\n");
19     else
20         System.out.println("f1 and f2 are not equal using threshold\n");
21 }

 

二、使用BigDecimal

注意:equals  會比較兩數的精度

1 private static void testBdEquality(){
2      BigDecimal a = new BigDecimal("2.00");
3      BigDecimal b = new BigDecimal("2.0");
4  
5      System.out.println(a.equals(b));           // false
6  
7      System.out.println(a.compareTo(b) == 0);   // true
8 }

例子:

 1 private static void bigDecimalComparison() {
 2     //Method 1
 3     BigDecimal f1 = new BigDecimal("0.0");
 4     BigDecimal pointOne = new BigDecimal("0.1");
 5     for (int i = 1; i <= 11; i++) {
 6         f1 = f1.add(pointOne);
 7     }
 8  
 9     //Method 2
10     BigDecimal f2 = new BigDecimal("0.1");
11     BigDecimal eleven = new BigDecimal("11");
12     f2 = f2.multiply(eleven);
13  
14     System.out.println("f1 = " + f1);
15     System.out.println("f2 = " + f2);
16  
17     if (f1.compareTo(f2) == 0)
18         System.out.println("f1 and f2 are equal using BigDecimal\n");
19     else
20         System.out.println("f1 and f2 are not equal using BigDecimal\n");
21 }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM