Debian Codegraph @

freehep-graphicsbase/src/main/java/org/freehep/graphicsbase/util/ScientificFormat.java

raw
1 package org.freehep.graphicsbase.util;
2
3 import java.text.DecimalFormat;
4 import java.text.DecimalFormatSymbols;
5 import java.text.FieldPosition;
6 import java.text.Format;
7 import java.text.ParsePosition;
8 import java.util.Locale;
9
10
11 /**
12 * This code formats numbers in Scientific Notation. The input Number object is returned
13 * as a ScientificFormated string. There are two output styles: Pure and Standard scientific
14 * notation. Pure formatted numbers have precisely the number of digits specified by the
15 * significant digits (sigDig) parameter and always specify a Base 10 Exponential(E).
16 * Standard formated numbers have the number of digits specified by the significant
17 * digits (sigDig) parameter but will not have a Base 10 Exponential(E) if the number of digits
18 * in the mantissa <= maxWidth.
19 *
20 * @author Paul Spence
21 * @author Mark Donszelmann
22 * @version $Id: ScientificFormat.java 8584 2006-08-10 23:06:37Z duns $
23 */
24
25 public class ScientificFormat extends Format
26 {
27 /**
28 * The number of significant digits the number is formatted to is recorded by sigDigit.
29 * The maximum width allowed for the returned String is recorded by MaxWidth
30 */
31 private int sigDigit = 5;
32 private int maxWidth = 8;
33 private boolean sciNote = false; //set to true for pure Scientific Notation
34 private DecimalFormat decimalFormat;
35 private static final long serialVersionUID = -1182686857248711235L;
36
37 public ScientificFormat()
38 {
39
40 }
41
42 /**
43 * Sets the significant digits, maximum allowable width and number formatting style
44 * (SciNote == true for Pure formatting).
45 */
46 public ScientificFormat(int sigDigit, int maxWidth, boolean SciNote)
47 {
48 setSigDigits(sigDigit);
49 setMaxWidth(maxWidth);
50 setScientificNotationStyle(SciNote);
51 }
52
53 /**
54 * Implementation of inherited abstract method. Checks to see if object to be formatted
55 * is of type Number. If so casts the Number object to double and calls the format method.
56 * Returns the result.
57 */
58 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos)
59 {
60 if (obj instanceof Number)
61 {
62 String result = format(((Number) obj).doubleValue());
63 return toAppendTo.append(result);
64 }
65 else if (obj instanceof DoubleWithError)
66 {
67 DoubleWithError dwe = (DoubleWithError) obj;
68 toAppendTo.append(format(dwe.getValue()));
69 if (dwe.hasAsymmetricError())
70 {
71 toAppendTo.append(DoubleWithError.plus);
72 int errorSigDigit = resolveErrorSigDigit(dwe.getValue(),dwe.getPlusError());
73 toAppendTo.append(format(dwe.getPlusError(),errorSigDigit));
74
75 toAppendTo.append(DoubleWithError.minus);
76 errorSigDigit = resolveErrorSigDigit(dwe.getValue(),dwe.getMinError());
77 toAppendTo.append(format(dwe.getMinError(),errorSigDigit));
78 }
79 else
80 {
81 toAppendTo.append(DoubleWithError.plusorminus);
82 int errorSigDigit = resolveErrorSigDigit(dwe.getValue(),dwe.getError());
83 toAppendTo.append(format(dwe.getError(),errorSigDigit));
84 }
85 return toAppendTo;
86 }
87 else throw new IllegalArgumentException("Cannot format given Object as a Number");
88 }
89
90 /**Dummy implementation of inherited abstract method.
91 */
92 public Object parseObject(String source, ParsePosition pos)
93 {
94 return null;
95 }
96
97 /**
98 * Returns the number of significant digits
99 */
100 public int getSigDigits()
101 {
102 return sigDigit;
103 }
104
105 /**
106 * Returns the maximum allowable width of formatted number excluding any exponentials
107 */
108 public int getMaxWidth()
109 {
110 return maxWidth;
111 }
112
113 /**
114 * Returns the formatting style: True means Pure scientific formatting, False means standard.
115 */
116 public boolean getScientificNotationStyle()
117 {
118 return sciNote;
119 }
120
121 /**
122 * Sets the number of significant digits for the formatted number
123 */
124 public void setSigDigits(int SigDigit)
125 {
126 if (SigDigit < 1) throw new IllegalArgumentException("sigDigit");
127 sigDigit = SigDigit;
128 decimalFormat = null;
129 }
130
131 /**
132 * Sets the maximum allowable length of the formattted number mantissa before exponential notation
133 * is used.
134 */
135 public void setMaxWidth(int mWidth)
136 {
137 if (mWidth < 3) throw new IllegalArgumentException("maxWidth");
138 maxWidth = mWidth;
139 }
140 /**
141 * Sets the format style used.
142 * There are two output styles: Pure and Standard scientific
143 * notation. Pure formatted numbers have precisely the number of digits specified by the
144 * significant digits (sigDig) parameter and always specify a Base 10 Exponential(E).
145 * Standard formated numbers have the number of digits specified by the significant
146 * digits (sigDig) parameter but will not have a Base 10 Exponential(E) if the number of digits
147 * in the mantissa <= maxWidth.
148 */
149 public void setScientificNotationStyle(boolean sciNote)
150 {
151 this.sciNote = sciNote;
152 }
153
154
155 //simplify method for taking log base 10 of x
156 private final static double k = 1/Math.log(10);
157 private double Log10(double x)
158 {
159 if (x==0) return 0;
160 else return Math.log(x)*k;
161 }
162
163 private int resolveErrorSigDigit(double x, double dx)
164 {
165 //dx should never be negative
166 dx = Math.abs(dx);
167 //make x +ve cause negative doesn't effect sigdigits
168 x=Math.abs(x);
169
170 //these circumstances errorsigdit does equal sigdigit, excluding infinity and Nan which are handled by format
171 if(dx == 0 || Double.isInfinite(dx) || Double.isNaN(dx) || dx >= x) return sigDigit;
172
173 //fail cases for log, method fails to handle
174 if(x==0||Double.isInfinite(x) || Double.isNaN(x))return sigDigit;
175
176 //otherwise solve for cases when dx<x
177 int log =(int)Math.round(Log10(dx/x));//always will return negative number
178 int errorsigdigit = sigDigit+log;
179 if(errorsigdigit <1) return 1;
180 return errorsigdigit;
181 }
182 private DecimalFormat getDecimalFormat(int sigDig)
183 {
184 StringBuffer buffer = new StringBuffer("0.");
185 for (int i=1; i<sigDig; i++) buffer.append('0');
186 buffer.append("E0");
187 return new DecimalFormat(buffer.toString(),new DecimalFormatSymbols(Locale.US));
188 }
189 /**
190 * Format the number using scientific notation
191 */
192 public String format(double d)
193 {
194 return format(d,sigDigit);
195 }
196 private String format(double d, int sigDig)
197 {
198 // Deal with a few special values first
199 if (Double.isInfinite(d)) return maxWidth < 8 ? "INF" : "Infinite";
200 if (Double.isNaN(d)) return "NaN";
201
202 // Delegate the hard part to decimalFormat
203 if (decimalFormat == null) decimalFormat = getDecimalFormat(sigDigit);
204 DecimalFormat format = (sigDig == sigDigit) ? decimalFormat : getDecimalFormat(sigDig);
205
206 String preliminaryResult = format.format(d);
207 if (sciNote) return preliminaryResult;
208
209 int ePos = preliminaryResult.indexOf('E');
210 int exponent = Integer.parseInt(preliminaryResult.substring(ePos+1))+1;
211 if (exponent>maxWidth) return preliminaryResult;
212 if (exponent<-maxWidth+sigDig+1) return preliminaryResult;
213
214 // We need to fix up the result
215
216 int sign = preliminaryResult.charAt(0)=='-' ? 1 : 0;
217 StringBuffer result = new StringBuffer(preliminaryResult.substring(sign,sign+1)+preliminaryResult.substring(sign+2,ePos));
218
219 if (exponent >= sigDig)
220 {
221 for (int i=sigDig; i<exponent; i++) result.append('0');
222 }
223 else if (exponent < 0)
224 {
225 result.insert(0,".");
226 for (int i=exponent; i<0; i++) result.insert(1,'0');
227 }
228 else
229 {
230 result.insert(exponent,'.');
231 }
232 if (sign > 0) result.insert(0,'-');
233 return result.toString();
234 }
235 // /**
236 // * Format a number plus error using scientific notation
237 // */
238 // public String formatError(double d,double dx)
239 // {
240 // return format(dx, resolveErrorSigDigit(d, dx));
241 // }
242
243 }