01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fit;
04:
05: // Copyright (c) 2002 Cunningham & Cunningham, Inc.
06: // Released under the terms of the GNU General Public License version 2 or later.
07:
08: // Warning: not (yet) a general number usable in all calculations.
09:
10: public class ScientificDouble extends Number implements Comparable {
11: private static final long serialVersionUID = 1L;
12:
13: protected double value;
14:
15: protected double precision;
16:
17: public ScientificDouble(double value) {
18: this .value = value;
19: this .precision = 0;
20: }
21:
22: public static ScientificDouble valueOf(String s) {
23: ScientificDouble result = new ScientificDouble(Double
24: .parseDouble(s));
25: result.precision = precision(s);
26: return result;
27: }
28:
29: public static ScientificDouble parse(String s) {
30: return valueOf(s);
31: }
32:
33: public static double precision(String s) {
34: double value = Double.parseDouble(s);
35: double bound = Double.parseDouble(tweak(s.trim()));
36: return Math.abs(bound - value);
37: }
38:
39: public static String tweak(String s) {
40: int pos;
41: if ((pos = s.toLowerCase().indexOf("e")) >= 0) {
42: return tweak(s.substring(0, pos)) + s.substring(pos);
43: }
44: if (s.indexOf(".") >= 0) {
45: return s + "5";
46: }
47: return s + ".5";
48: }
49:
50: public boolean equals(Object obj) {
51: return compareTo(obj) == 0;
52: }
53:
54: public int compareTo(Object obj) {
55: double other = ((Number) obj).doubleValue();
56: double diff = value - other;
57: // System.out.println(value+" "+precision+" "+diff);
58: if (diff < -precision)
59: return -1;
60: if (diff > precision)
61: return 1;
62: if (Double.isNaN(value) && Double.isNaN(other))
63: return 0;
64: if (Double.isNaN(value))
65: return 1;
66: if (Double.isNaN(other))
67: return -1;
68: return 0;
69: }
70:
71: public String toString() {
72: return Double.toString(value);
73: }
74:
75: public double doubleValue() {
76: return value;
77: }
78:
79: public float floatValue() {
80: return (float) value;
81: }
82:
83: public long longValue() {
84: return (long) value;
85: }
86:
87: public int intValue() {
88: return (int) value;
89: }
90: }
|