View Javadoc

1   package fit;
2   
3   // Copyright (c) 2002 Cunningham & Cunningham, Inc.
4   // Released under the terms of the GNU General Public License version 2 or later.
5   
6   // Warning: not (yet) a general number usable in all calculations.
7   
8   public class ScientificDouble extends Number implements Comparable {
9       protected double value;
10      protected double precision;
11  
12      public ScientificDouble(double value) {
13          this.value = value;
14          this.precision = 0;
15      }
16  
17      public static ScientificDouble valueOf(String s) {
18          ScientificDouble result = new ScientificDouble(Double.parseDouble(s));
19          result.precision = precision(s);
20          return result;
21      }
22  
23      public static double precision (String s) {
24          double value = Double.parseDouble(s);
25          double bound = Double.parseDouble(tweak(s.trim()));
26          return Math.abs(bound-value);
27      }
28  
29      public static String tweak(String s) {
30          int pos;
31          if ((pos = s.toLowerCase().indexOf("e"))>=0) {
32              return tweak(s.substring(0,pos)) + s.substring(pos);
33          }
34          if (s.indexOf(".")>=0) {
35              return s + "5";
36          }
37          return s+".5";
38      }
39  
40  
41  
42      public boolean equals(Object obj) {
43          return compareTo(obj) == 0;
44      }
45  
46      public int compareTo(Object obj) {
47          double other = ((Number)obj).doubleValue();
48          double diff = value-other;
49          // System.out.println(value+" "+precision+" "+diff);
50          if (diff < -precision) return -1;
51          if (diff > precision) return 1;
52          if (Double.isNaN(value) && Double.isNaN(other)) return 0;
53          if (Double.isNaN(value)) return 1;
54          if (Double.isNaN(other)) return -1;
55          return 0;
56      }
57  
58      public String toString() {
59          return Double.toString(value);
60      }
61  
62      public double doubleValue() {
63          return value;
64      }
65  
66      public float floatValue() {
67          return (float)value;
68      }
69  
70      public long longValue() {
71          return (long)value;
72      }
73  
74      public int intValue() {
75          return (int)value;
76      }
77  }