views:

702

answers:

4

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:

1/(z+1)
(z^2)/(z/2)

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?

A: 

I would (and have, actually) manually make a parse table and use a simple LR or LALR parser to process it. At a reduction, you can perform the calculations. One advantage to this is that it is easy to modify the "language", or acceptable input.

xpda
A: 

Here's crazy solution: java has built-in JavaScript engine (I suppose you can access it from Processing). Now, you write a javascript class that works with complex numbers(copy it from here). Then, overload math operators as specified here. AFter that you can just eval this string from java. It's crazy and I'm not sure that it will work (i don't know javascript). Maybe it will make to find some simplier solution without parsing expressions.

tulskiy
+1  A: 

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");
textFont(loadFont("UMingCN-30.vlw"));
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();
  parser.addComplex();
  try {
    parser.parseExpression("(1+2*i) + (3+8*i)");
    println(parser.getComplexValue());
  } catch(Exception e) {
    e.printStackTrace();
  }
}

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

Bart Kiers
Why would they charge you $500 if there's a GPL version?
tulskiy
Thanks so much, it works well (and generics save typing time). I can't understand the $500/GPL discrepancy though.
Callum Rogers
AFAIK, JEP started out as a GPL application (or some other open license). A while back, they turned commercial and from then on, an old(er) version of JEP was hosted at Sourceforge. You can't just go charging people money who have been using the GPL-ed software for years after all.
Bart Kiers
A: 

Here is a link to a straight-forward math expression parser (64 lines): http://javadots.blogspot.com/2008/11/arithemetic-expressions-solver-in-64.html

Tweaking it to support your needs should not be too difficult

Itay