Callum Rogers Callum Rogers - 2 years ago 86
Java Question

Java math expression parser that can take complex numbers as a variable?

I am writing a program in Processing that transforms complex numbers. However, I want to have a method of taking an input string and calculating the transformation using a complex variable. For example:


where z is a complex number. Now, I've looked at JEP and some examples, but I cannot work out if it would allow you to actually enter z as a variable (and in any case it is not free). Is there an expression parser for Java (that works in processing, which uses an old version of java and does not have generics) that I could use to do this?

If there is not, could someone point me to the basics of how to create one?

Answer Source

As mentioned by PhiLo, you can use generics. Try this Processing sketch:

import java.util.*;
java.util.List<String> list = Arrays.asList("a", "b", "c");
for(int i = 0; i < list.size(); i++) {
  text(list.get(i), 5, int(i*30)+30);

And there's a non commercial version of JEP available (GPL). Download it here and add it to your Processing classpath (import it). After successfully doing so, you can use JEP like this:

void setup() {
  org.nfunk.jep.JEP parser = new org.nfunk.jep.JEP();
  try {
    parser.parseExpression("(1+2*i) + (3+8*i)");
  } catch(Exception e) {

which produces the (expected) output: (4.0, 10.0)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download