Pattern Matching in Java
I'm working on java program that can compute the differentiation of any gi开发者_如何学编程ven 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..
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:
Best algorithm for evaluating a mathematical expression?
Reading and running a mathematical expression in Python
Evaluating mathematical expressions
JEval is a decent alternative, seeing as JEP is now under a commercial license.
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
If you want to code it yourself then you can use Polish notation which is widely used for this purpose.
Another alternative is the JScience library. The abstract class Function includes a differentiate()
method, which is implemented for discrete, polynomial, and rational functions.
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:
- Symja/Matheclipse (my own project)
- MathPiper (a Java fork of the Yacas project)
- omath.org (SVN at omath.org site seems to work?)
精彩评论