user1791473
user1791473

Reputation: 81

How to scan complex numbers in java

How can i scan number inserted in this form: 1.7+2.8990i in java? I imagine its possible to split the line one time with +, or -? How should i take this line as a string or sth else?

Thanks

Upvotes: 2

Views: 1162

Answers (2)

Jason Sperske
Jason Sperske

Reputation: 30446

Here is a RegEx approach (without external library but also without ability to use a Complex Number for more than just parsing):

Pattern pattern = Pattern.compile("([+-]?\\d*\\.\\d+)([+-]?\\d*\\.\\d+)i",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher matcher = pattern.matcher("1.7+2.8990i");
if(matcher.matches()) {
  System.out.println("a:" + Float.parseFloat(matcher.group(1)));
  System.out.println("b:" + Float.parseFloat(matcher.group(2)));
} else {
  System.out.println("Not a complex number");
}

This approach supports positive and negative values for a and b. Now one weaknesses to this approach are it doesn't tolerate spaces around number (you could safely strip spaces from your input and not alter the equation).

Upvotes: 1

Jason Sperske
Jason Sperske

Reputation: 30446

If you wanted to use a library there is always Commons Math which lets you do stuff like this:

ComplexFormat cf = new ComplexFormat();
Complex c = cf.parse("1.110 + 2.222i");
Complex second = new Complex(2.0, 5.0);
Complex answer = c.log();        // natural logarithm.
        answer = c.cos();        // cosine
        answer = c.pow(second);  // first raised to the power of second

ComplexFormat format = new ComplexFormat(); // default format
String s1 = format.format(c);      // s1 contains "1.110 + 2.222i"
String s2 = format.format(second); // s2 contains "2.0 + 5.0i"

Upvotes: 3

Related Questions