001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 package org.apache.commons.math.complex;
019
020 import java.text.FieldPosition;
021 import java.text.NumberFormat;
022 import java.text.ParseException;
023 import java.text.ParsePosition;
024 import java.util.Locale;
025
026 import org.apache.commons.math.MathRuntimeException;
027 import org.apache.commons.math.util.CompositeFormat;
028
029 /**
030 * Formats a Complex number in cartesian format "Re(c) + Im(c)i". 'i' can
031 * be replaced with 'j' (or anything else), and the number format for both real
032 * and imaginary parts can be configured.
033 *
034 * @author Apache Software Foundation
035 * @version $Revision: 772119 $ $Date: 2009-05-06 05:43:28 -0400 (Wed, 06 May 2009) $
036 */
037 public class ComplexFormat extends CompositeFormat {
038
039 /** Serializable version identifier */
040 private static final long serialVersionUID = -3343698360149467646L;
041
042 /** The default imaginary character. */
043 private static final String DEFAULT_IMAGINARY_CHARACTER = "i";
044
045 /** The notation used to signify the imaginary part of the complex number. */
046 private String imaginaryCharacter;
047
048 /** The format used for the imaginary part. */
049 private NumberFormat imaginaryFormat;
050
051 /** The format used for the real part. */
052 private NumberFormat realFormat;
053
054 /**
055 * Create an instance with the default imaginary character, 'i', and the
056 * default number format for both real and imaginary parts.
057 */
058 public ComplexFormat() {
059 this(DEFAULT_IMAGINARY_CHARACTER, getDefaultNumberFormat());
060 }
061
062 /**
063 * Create an instance with a custom number format for both real and
064 * imaginary parts.
065 * @param format the custom format for both real and imaginary parts.
066 */
067 public ComplexFormat(NumberFormat format) {
068 this(DEFAULT_IMAGINARY_CHARACTER, format);
069 }
070
071 /**
072 * Create an instance with a custom number format for the real part and a
073 * custom number format for the imaginary part.
074 * @param realFormat the custom format for the real part.
075 * @param imaginaryFormat the custom format for the imaginary part.
076 */
077 public ComplexFormat(NumberFormat realFormat, NumberFormat imaginaryFormat) {
078 this(DEFAULT_IMAGINARY_CHARACTER, realFormat, imaginaryFormat);
079 }
080
081 /**
082 * Create an instance with a custom imaginary character, and the default
083 * number format for both real and imaginary parts.
084 * @param imaginaryCharacter The custom imaginary character.
085 */
086 public ComplexFormat(String imaginaryCharacter) {
087 this(imaginaryCharacter, getDefaultNumberFormat());
088 }
089
090 /**
091 * Create an instance with a custom imaginary character, and a custom number
092 * format for both real and imaginary parts.
093 * @param imaginaryCharacter The custom imaginary character.
094 * @param format the custom format for both real and imaginary parts.
095 */
096 public ComplexFormat(String imaginaryCharacter, NumberFormat format) {
097 this(imaginaryCharacter, format, (NumberFormat)format.clone());
098 }
099
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 }