View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.math.complex;
19  
20  import java.text.FieldPosition;
21  import java.text.NumberFormat;
22  import java.text.ParseException;
23  import java.text.ParsePosition;
24  import java.util.Locale;
25  
26  import org.apache.commons.math.MathRuntimeException;
27  import org.apache.commons.math.util.CompositeFormat;
28  
29  /**
30   * Formats a Complex number in cartesian format "Re(c) + Im(c)i".  'i' can
31   * be replaced with 'j' (or anything else), and the number format for both real
32   * and imaginary parts can be configured.
33   *
34   * @author Apache Software Foundation
35   * @version $Revision: 772119 $ $Date: 2009-05-06 05:43:28 -0400 (Wed, 06 May 2009) $
36   */
37  public class ComplexFormat extends CompositeFormat {
38      
39      /** Serializable version identifier */
40      private static final long serialVersionUID = -3343698360149467646L;
41  
42       /** The default imaginary character. */
43      private static final String DEFAULT_IMAGINARY_CHARACTER = "i";
44      
45      /** The notation used to signify the imaginary part of the complex number. */
46      private String imaginaryCharacter;
47      
48      /** The format used for the imaginary part. */
49      private NumberFormat imaginaryFormat;
50  
51      /** The format used for the real part. */
52      private NumberFormat realFormat;
53      
54      /**
55       * Create an instance with the default imaginary character, 'i', and the
56       * default number format for both real and imaginary parts.
57       */
58      public ComplexFormat() {
59          this(DEFAULT_IMAGINARY_CHARACTER, getDefaultNumberFormat());
60      }
61  
62      /**
63       * Create an instance with a custom number format for both real and
64       * imaginary parts.
65       * @param format the custom format for both real and imaginary parts.
66       */
67      public ComplexFormat(NumberFormat format) {
68          this(DEFAULT_IMAGINARY_CHARACTER, format);
69      }
70      
71      /**
72       * Create an instance with a custom number format for the real part and a
73       * custom number format for the imaginary part.
74       * @param realFormat the custom format for the real part.
75       * @param imaginaryFormat the custom format for the imaginary part.
76       */
77      public ComplexFormat(NumberFormat realFormat, NumberFormat imaginaryFormat) {
78          this(DEFAULT_IMAGINARY_CHARACTER, realFormat, imaginaryFormat);
79      }
80      
81      /**
82       * Create an instance with a custom imaginary character, and the default
83       * number format for both real and imaginary parts.
84       * @param imaginaryCharacter The custom imaginary character.
85       */
86      public ComplexFormat(String imaginaryCharacter) {
87          this(imaginaryCharacter, getDefaultNumberFormat());
88      }
89      
90      /**
91       * Create an instance with a custom imaginary character, and a custom number
92       * format for both real and imaginary parts.
93       * @param imaginaryCharacter The custom imaginary character.
94       * @param format the custom format for both real and imaginary parts.
95       */
96      public ComplexFormat(String imaginaryCharacter, NumberFormat format) {
97          this(imaginaryCharacter, format, (NumberFormat)format.clone());
98      }
99      
100     /**
101      * Create an instance with a custom imaginary character, a custom number
102      * format for the real part, and a custom number format for the imaginary
103      * part.
104      * @param imaginaryCharacter The custom imaginary character.
105      * @param realFormat the custom format for the real part.
106      * @param imaginaryFormat the custom format for the imaginary part.
107      */
108     public ComplexFormat(String imaginaryCharacter, NumberFormat realFormat,
109             NumberFormat imaginaryFormat) {
110         super();
111         setImaginaryCharacter(imaginaryCharacter);
112         setImaginaryFormat(imaginaryFormat);
113         setRealFormat(realFormat);
114     }
115 
116     /**
117      * Get the set of locales for which complex formats are available.
118      * <p>This is the same set as the {@link NumberFormat} set.</p> 
119      * @return available complex format locales.
120      */
121     public static Locale[] getAvailableLocales() {
122         return NumberFormat.getAvailableLocales();
123     }
124 
125     /**
126      * This static method calls {@link #format(Object)} on a default instance of
127      * ComplexFormat.
128      *
129      * @param c Complex object to format
130      * @return A formatted number in the form "Re(c) + Im(c)i"
131      */
132     public static String formatComplex(Complex c) {
133         return getInstance().format(c);
134     }
135     
136     /**
137      * Formats a {@link Complex} object to produce a string.
138      *
139      * @param complex the object to format.
140      * @param toAppendTo where the text is to be appended
141      * @param pos On input: an alignment field, if desired. On output: the
142      *            offsets of the alignment field
143      * @return the value passed in as toAppendTo.
144      */
145     public StringBuffer format(Complex complex, StringBuffer toAppendTo,
146             FieldPosition pos) {
147         
148         pos.setBeginIndex(0);
149         pos.setEndIndex(0);
150 
151         // format real
152         double re = complex.getReal();
153         formatDouble(re, getRealFormat(), toAppendTo, pos);
154         
155         // format sign and imaginary
156         double im = complex.getImaginary();
157         if (im < 0.0) {
158             toAppendTo.append(" - ");
159             formatDouble(-im, getImaginaryFormat(), toAppendTo, pos);
160             toAppendTo.append(getImaginaryCharacter());
161         } else if (im > 0.0 || Double.isNaN(im)) {
162             toAppendTo.append(" + ");
163             formatDouble(im, getImaginaryFormat(), toAppendTo, pos);
164             toAppendTo.append(getImaginaryCharacter());
165         }
166         
167         return toAppendTo;
168     }
169     
170     /**
171      * Formats a object to produce a string.  <code>obj</code> must be either a 
172      * {@link Complex} object or a {@link Number} object.  Any other type of
173      * object will result in an {@link IllegalArgumentException} being thrown.
174      *
175      * @param obj the object to format.
176      * @param toAppendTo where the text is to be appended
177      * @param pos On input: an alignment field, if desired. On output: the
178      *            offsets of the alignment field
179      * @return the value passed in as toAppendTo.
180      * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
181      * @throws IllegalArgumentException is <code>obj</code> is not a valid type.
182      */
183     @Override
184     public StringBuffer format(Object obj, StringBuffer toAppendTo,
185             FieldPosition pos) {
186         
187         StringBuffer ret = null;
188         
189         if (obj instanceof Complex) {
190             ret = format( (Complex)obj, toAppendTo, pos);
191         } else if (obj instanceof Number) {
192             ret = format( new Complex(((Number)obj).doubleValue(), 0.0),
193                 toAppendTo, pos);
194         } else { 
195             throw MathRuntimeException.createIllegalArgumentException(
196                   "cannot format a {0} instance as a complex number",
197                   obj.getClass().getName());
198         }
199         
200         return ret;
201     }
202 
203     /**
204      * Access the imaginaryCharacter.
205      * @return the imaginaryCharacter.
206      */
207     public String getImaginaryCharacter() {
208         return imaginaryCharacter;
209     }
210     
211     /**
212      * Access the imaginaryFormat.
213      * @return the imaginaryFormat.
214      */
215     public NumberFormat getImaginaryFormat() {
216         return imaginaryFormat;
217     }
218     
219     /**
220      * Returns the default complex format for the current locale.
221      * @return the default complex format.
222      */
223     public static ComplexFormat getInstance() {
224         return getInstance(Locale.getDefault());
225     }
226     
227     /**
228      * Returns the default complex format for the given locale.
229      * @param locale the specific locale used by the format.
230      * @return the complex format specific to the given locale.
231      */
232     public static ComplexFormat getInstance(Locale locale) {
233         NumberFormat f = getDefaultNumberFormat(locale);
234         return new ComplexFormat(f);
235     }
236     
237     /**
238      * Access the realFormat.
239      * @return the realFormat.
240      */
241     public NumberFormat getRealFormat() {
242         return realFormat;
243     }
244 
245     /**
246      * Parses a string to produce a {@link Complex} object.
247      *
248      * @param source the string to parse
249      * @return the parsed {@link Complex} object.
250      * @exception ParseException if the beginning of the specified string
251      *            cannot be parsed.
252      */
253     public Complex parse(String source) throws ParseException {
254         ParsePosition parsePosition = new ParsePosition(0);
255         Complex result = parse(source, parsePosition);
256         if (parsePosition.getIndex() == 0) {
257             throw MathRuntimeException.createParseException(
258                     parsePosition.getErrorIndex(),
259                     "unparseable complex number: \"{0}\"", source);
260         }
261         return result;
262     }
263     
264     /**
265      * Parses a string to produce a {@link Complex} object.
266      *
267      * @param source the string to parse
268      * @param pos input/ouput parsing parameter.
269      * @return the parsed {@link Complex} object.
270      */
271     public Complex parse(String source, ParsePosition pos) {
272         int initialIndex = pos.getIndex();
273 
274         // parse whitespace
275         parseAndIgnoreWhitespace(source, pos);
276 
277         // parse real
278         Number re = parseNumber(source, getRealFormat(), pos);
279         if (re == null) {
280             // invalid real number
281             // set index back to initial, error index should already be set
282             pos.setIndex(initialIndex);
283             return null;
284         }
285 
286         // parse sign
287         int startIndex = pos.getIndex();
288         char c = parseNextCharacter(source, pos);
289         int sign = 0;
290         switch (c) {
291         case 0 :
292             // no sign
293             // return real only complex number
294             return new Complex(re.doubleValue(), 0.0);
295         case '-' :
296             sign = -1;
297             break;
298         case '+' :
299             sign = 1;
300             break;
301         default :
302             // invalid sign
303             // set index back to initial, error index should be the last
304             // character examined.
305             pos.setIndex(initialIndex);
306             pos.setErrorIndex(startIndex);
307             return null;
308         }
309 
310         // parse whitespace
311         parseAndIgnoreWhitespace(source, pos);
312 
313         // parse imaginary
314         Number im = parseNumber(source, getRealFormat(), pos);
315         if (im == null) {
316             // invalid imaginary number
317             // set index back to initial, error index should already be set
318             pos.setIndex(initialIndex);
319             return null;
320         }
321 
322         // parse imaginary character
323         if (!parseFixedstring(source, getImaginaryCharacter(), pos)) {
324             return null;
325         }
326 
327         return new Complex(re.doubleValue(), im.doubleValue() * sign);
328 
329     }
330      
331     /**
332      * Parses a string to produce a object.
333      *
334      * @param source the string to parse
335      * @param pos input/ouput parsing parameter.
336      * @return the parsed object.
337      * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition)
338      */
339     @Override
340     public Object parseObject(String source, ParsePosition pos) {
341         return parse(source, pos);
342     }
343 
344     /**
345      * Modify the imaginaryCharacter.
346      * @param imaginaryCharacter The new imaginaryCharacter value.
347      * @throws IllegalArgumentException if <code>imaginaryCharacter</code> is
348      *         <code>null</code> or an empty string.
349      */
350     public void setImaginaryCharacter(String imaginaryCharacter) {
351         if (imaginaryCharacter == null || imaginaryCharacter.length() == 0) {
352             throw MathRuntimeException.createIllegalArgumentException(
353                   "empty string for imaginary character");
354         }
355         this.imaginaryCharacter = imaginaryCharacter;
356     }
357     
358     /**
359      * Modify the imaginaryFormat.
360      * @param imaginaryFormat The new imaginaryFormat value.
361      * @throws IllegalArgumentException if <code>imaginaryFormat</code> is
362      *         <code>null</code>.
363      */
364     public void setImaginaryFormat(NumberFormat imaginaryFormat) {
365         if (imaginaryFormat == null) {
366             throw MathRuntimeException.createIllegalArgumentException(
367                   "null imaginary format");
368         }
369         this.imaginaryFormat = imaginaryFormat;
370     }
371     
372     /**
373      * Modify the realFormat.
374      * @param realFormat The new realFormat value.
375      * @throws IllegalArgumentException if <code>realFormat</code> is
376      *         <code>null</code>.
377      */
378     public void setRealFormat(NumberFormat realFormat) {
379         if (realFormat == null) {
380             throw MathRuntimeException.createIllegalArgumentException(
381                   "null real format");
382         }
383         this.realFormat = realFormat;
384     }
385 
386 }