Added parse() method to Complex(). TODO: Add testing.
@@ -20,6 +20,7 @@ package org.apache.commons.numbers.complex;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
+import java.lang.NumberFormatException;
import org.apache.commons.numbers.core.Precision;
/**
* Representation of a Complex number, i.e. a number which has both a
@@ -131,6 +132,40 @@ public final class Complex implements Serializable {
return new Complex(Math.cos(x), Math.sin(x));
}
+ /**
+ * Parses a text expression in a String object to produce
+ * a Cartesian complex number. Acceptable formats are:
+ * <p><ul> * <li>Single number (parsed as real). Example: "3.14"
+ * <li>Single number with appended "i" (parsed as imaginary): "1.42i"
+ * <li>Pair of numbers, separated by plus sign and with appended i: "3 + 4i"
+ * </ul>
+ * @throws{ParseException, NumberFormatException}
+ */
+ public static Complex parse(String s) {
+ final String[] terms = s.split("+");
+ if (terms.length == 2) {
+ if (terms[1].indexOf("i") == terms[1].length()) {
+ String imagTerm = (String) terms[1].subSequence(0, terms[1].length()-1);
+ final double real = Double.parseDouble(terms[0]);
+ final double imaginary = Double.parseDouble(imagTerm);
+ return Complex.ofCartesian(real, imaginary);
+ } else {
+ throw new NumberFormatException("Expression must end with unique \"i\"");
+ }
+ } else if (terms.length == 1){
+ if (terms[0].indexOf("i") == terms[0].length()) {
+ String imagTerm = (String) terms[0].subSequence(0, terms[0].length()-1);
+ final double imaginary = Double.parseDouble(imagTerm);
+ return Complex.ofCartesian(0, imaginary);
+ } else {
+ final double real = Double.parseDouble(terms[0]);
+ return Complex.ofReal(real);
+ }
+ } else {
+ throw new NumberFormatException("Invalid expression for Complex. See documentation for further information.");
+ }
+ }
+
/**
* Returns true if either real or imaginary component of the Complex
* is NaN
