tags:

views:

225

answers:

6

I'm working on java program that can compute the differentiation of any given mathematical expression. When User types the expression say Sin(Cos(x^2)) I need to check whether it is mathematically valid or not. Of course we can do it by manual code writing but that would be tedious work. Can I do it using regex package of java??

How??

thanx..

+2  A: 

if you are trying to accept any mathematical expression then regex will not work for you.

you will need to use a parser to check your expression and decide if its valid or not base on a specified mathematical grammar.

have a lot at antlr

Alon
+9  A: 

No, regexes aren't sufficient... (in fact, this can be mathematically proved).

To parse mathematical expressions, you can either write your own parser (which isn't actually that hard) or use an existing one, such as Jep.

Here are some previous SO questions on parsing mathematical expressions:

http://stackoverflow.com/questions/572796/best-algorithm-for-evaluating-a-mathematical-expression

http://stackoverflow.com/questions/400050/reading-and-running-a-mathematical-expression-in-python

http://stackoverflow.com/questions/1151127/evaluating-mathematical-expressions

Martin B
+6  A: 

JEval is a decent alternative, seeing as JEP is now under a commercial license.

gpampara
+1  A: 

Another alternative is the JScience library. The abstract class Function includes a differentiate() method, which is implemented for discrete, polynomial, and rational functions.

trashgod
+2  A: 

If you want to code it yourself then you can use Polish notation which is widely used for this purpose.

Roman
A: 

Computer algebra systems (like for example Mathematica) use rule notations like the following for differentiation:

  D[Cos[x_],y_]:=(-1)*Sin[x]*D[x,y]
  D[Sin[x_],y_]:=Cos[x]*D[x,y]

these transformation rules are also sometimes called "pattern-matching rules", but they have nothing to do with regex pattern-matching for strings. See Introduction to Patterns for more information.

I know these open source Java projects, which contain a similar pattern-matching rule engine:

axelclk