Skip to content

Commit

Permalink
NUMBERS-68: Added parse() method to Complex(). TODO: Add testing.
Browse files Browse the repository at this point in the history
  • Loading branch information
ericbarnhill committed Apr 24, 2018
1 parent c2fadea commit d22b6d8
Showing 1 changed file with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
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
Expand Down Expand Up @@ -131,6 +132,40 @@ public static Complex ofCis(double x) {
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
Expand Down

0 comments on commit d22b6d8

Please sign in to comment.