I am looking for a matrix expression parser/engine. For example,
3 * A + B * C
where A, B, C are matrices is a typical expression. This should be similar to (single value) math expression parser/engine but should handle matrix value and variable. I've already googled in vain. I am also willing to modify existing math expression parser but I am not sure how I can go about it. So if you can give me any clue or hint, I will appreciate it.
See my answer on how to build simple parsers. This especially suited for expression parsers.
It is pretty easy to modify such a parser to compute the answer as it parses. Just add an action routine whenever the parser recognizes syntax, to do what the syntax says.
Related
I'm working on a tool in the context of a java project to evaluate a custom domain specific, rule-like expression like
min-5 avg datalist > Number
with the individual tokens meaning the following:
min-5 : optional minimum (or maximum, in that case max-5) occurences of the following term
avg : an optional aggregation function which operates on the following token datalist (can also be sum or anything similar)
datalist : A list of data (type: integer/ double) which will be available before the evaluation of the entire expression starts, can be reduced to a single value by the preceding aggregation function
operator: conditional operator < or > or =
Number: value for the conditional operator
Note(s):
The optional amount of occurrences and the aggregation can not happen both, that would make no sense.
There can be multiple of the above expressions, chained with and/or
These expressions are external input, not pre-defined
The evaluation of this expression should output a boolean
As I am rather new to expression evaluation / parsing I am searching for an elegant way to solve this, possibly with a java framework/tool.
What I've tried so far:
Parsing by hand which turned out not so nicely
Trying to use Janino Expression Evaluator, but I don't know how to handle this programmatically
I am searching for a solution to solve this in an elegant way, I am thankful for any suggestions
what you try to do is a DSL (domain specific language) and the elegant way to solve your issue is to create a grammar for yuor specific language that help you on parsing function.
Take a look at JavaCC or Antlr.
I have to give the user the option to enter in a text field a mathematical formula and then save it in the DB as a String. That is easy enough, but I also need to retrieve it and use it to do calculations.
For example, assume I allow someone to specify the formula of employee salary calculation which I must save in String format in the DB.
GROSS_PAY = BASIC_SALARY - NO_PAY + TOTAL_OT + ALLOWANCE_TOTAL
Assume that terms such as GROSS_PAY, BASIC_SALARY are known to us and we can make out what they evaluate to. The real issue is we can't predict which combinations of such terms (e.g. GROSS_PAY etc.) and other mathematical operators the user may choose to enter (not just the +, -, ×, / but also the radical sigh - indicating roots - and powers etc. etc.). So how do we interpret this formula in string format once where have retrieved it from DB, so we can do calculations based on the composition of the formula.
Building an expression evaluator is actually fairly easy.
See my SO answer on how to write a parser. With a BNF for the range of expression operators and operands you exactly want, you can follow this process to build a parser for exactly those expressions, directly in Java.
The answer links to a second answer that discusses how to evaluate the expression as you parse it.
So, you read the string from the database, collect the set of possible variables that can occur in the expression, and then parse/evaluate the string. If you don't know the variables in advance (seems like you must), you can parse the expression twice, the first time just to get the variable names.
as of Evaluating a math expression given in string form there is a JavaScript Engine in Java which can execute a String functionality with operators.
Hope this helps.
You could build a string representation of a class that effectively wraps your expression and compile it using the system JavaCompiler — it requires a file system. You can evaluate strings directly using javaScript or groovy. In each case, you need to figure out a way to bind variables. One approach would be to use regex to find and replace known variable names with a call to a binding function:
getValue("BASIC_SALARY") - getValue("NO_PAY") + getValue("TOTAL_OT") + getValue("ALLOWANCE_TOTAL")
or
getBASIC_SALARY() - getNO_PAY() + getTOTAL_OT() + getALLOWANCE_TOTAL()
This approach, however, exposes you to all kinds of injection type security bugs; so, it would not be appropriate if security was required. The approach is also weak when it comes to error diagnostics. How will you tell the user why their expression is broken?
An alternative is to use something like ANTLR to generate a parser in java. It's not too hard and there are a lot of examples. This approach will provide both security (users can't inject malicious code because it won't parse) and diagnostics.
Currently trying to do a reverse polish calculator for one of my Uni homework tasks.
I have the program working fine when using a bunch of if/else statements to work out which operator was typed in and do the mathematical operation normally like num1+num2.
This is beyond the homework task we were set but what I'm trying to do now is replace the operator with a variable for example: "num1 + num2" would become "num1 variable num2" where variable equals "+" etc.
Is there a way to do this in Java?
Thanks in advance
Since you are interested in going beyond the scope of the training material, and assuming you've learned about interfaces already, I believe what you are looking for is a binary expression tree (that wikipedia article actually explains it good).
Basically, you create an interface Expression with a double compute() method. There will be two types of implementing classes:
Operand: Constant and Variable.
Operator: Plus, Minus, Multiply, Divide. Each will have two Expression fields: left and right.
Your text expression is then parsed into the expression tree:
// input: "num1 + num2 * 3"
// result expression tree will be built by parser using:
Expression a = new Variable("num1");
Expression b = new Variable("num2");
Expression c = new Constant(3);
Expression d = new Multiply(b, c);
Expression e = new Plus(a, d);
Map<String, Double> variables = /*defined elsewhere*/;
double result = e.compute(variables);
Your new assignment, should you choose to accept it, will be to write the expression classes and a parser to build the expression tree from a text expression.
Hope this will encourage you to go way beyond the training material, having some fun while playing.
First you can use a switch on String rather than if-then-else chain. Another way is to build a static final Map (E.g. HashMap) from String to Function. The strings are the operators. The Functions do the operation. In Java 8 you can give the functions as lambdas. I only have access through a phone right now so can't show code. Your question will be much better received if you add code showing what you mean.
For a programming project in Calculus we were instructed to code a program that models the Simpson's 1/3 and 3/8 rule.
We are supposed to take in a polynomial(i.e. 5x^2+7x+10) but I am struggling conceptualizing this. I have began by using scanner but is there a better way to correctly read the polynomial?
Any examples or reference materials will be greatly appreciated.
I'd suggest that you start with a Function interface that takes in a number of input values and returns an output value:
public interface Function {
double evaluate(double x);
}
Write a polynomial implementation:
public class Poly {
public static double evaluate(double x, double [] coeffs) {
double value = 0.0;
if (coeffs != null) {
// Use Horner's method to evaluate.
for (int i = coeffs.length-1; i >= 0; --i) {
value = coeffs[i] + (x*value);
}
}
return value;
}
}
Pass that to your integrator and let it do its thing.
A simple way (to get you started) is to use an array.
In your example: 5x^2 + 7x + 10 would be:
{10,7,5}
I.e. at index 0 is the factor 10 for x^0 at index 1 is 7 for x^1 at index 2 is 10 for x^2.
Of course this not the best approach. To figure out way figure out how you would represent x^20
In java it would be easiest to pre-format your input and just ask for constants--as in, "Please enter the X^2 term" (and then the X term, and then the constant).
If that's not acceptable, you are going to be quite vulnerable to input style differences. You can separate the terms by String.split[ting] on + and -, that will leave you something like:
[5x^2], [7x], [10]
You could then search for strings containing "x^2" and "x" to differentiate your terms
Remove spaces and .toLowerCase() first to counter user variances, of course.
When you split your string you will need to identify the - cases so you can negate those constants.
You could do two splits, one on + the other on -. You could also use StringTokenizer with the option to keep the "Tokens" which might be more straight-forward but StringTokenizer makes some people a little uncomfortable, so go with whatever works for you.
Note that this will succeed even if the user types "5x^2 + 10 + 7 x", which can be handy.
I believe parsing is my problem. I am somewhat new to java so this is troubling me.
You should use a parser generator.
A parser generator is a tool that reads a grammar specification and converts it to a Java program that can recognize matches to the grammar. In addition to the parser generator itself, JavaCC provides other standard capabilities related to parser generation such as tree building (via a tool called JJTree included with JavaCC), actions, debugging, etc.
JavaCC's FAQ answers How do I parse arithmetic expressions?
See the examples that come with JavaCC.
See any text on compiling.
See Parsing Epressions by Recursive Descent and a tutorial by Theodore Norvell.
Also, see JavaCC - Parse math expressions into a class structure
I'm trying to find something like Java Embedding Plugin (JEP) that can evaluate a mathematical formula (string) and give back the answer.
But it should also calculate a variable, for example: (25+36+x)*2 = 25 should give: x = -11
A little like http://www.wolframalpha.com/, but it shouldn't be that versatile, and it should work off-line.
Open source is preferred.
I need it for my little calculator project, http://sourceforge.net/projects/calex/.
This is called Arithmetic evaluation. One of the easiest way to implement this is using Edsger Dijkstra Shunting-yard_algorithm.
The shunting-yard algorithm is a
method for parsing mathematical
equations specified in infix notation.
It can be used to produce output in
Reverse Polish notation (RPN) or as an
abstract syntax tree (AST). The
algorithm was invented by Edsger
Dijkstra and named the "shunting yard"
algorithm because its operation
resembles that of a railroad shunting
yard. Like the evaluation of RPN, the
shunting yard algorithm is
stack-based. Infix expressions are the
form of mathematical notation most
people are used to, for instance 3+4
or 3+4*(2−1). For the conversion there
are two text variables (strings), the
input and the output. There is also a
stack that holds operators not yet
added to the output queue. To convert,
the program reads each symbol in order
and does something based on that
symbol.
But I have seen exact solution what you are looking for on some stackoverflow user blog, but I can't remember the address (it was like 'code monkeyism'). It was lightweight class, that you could use in applets (you could also define constants and reset values).
Edit: Found it: http://tech.dolhub.com/Code/MathEval
A Linear-Recursive Math Evaluator
This math expression evaluator was born out of a need to have a small-footprint and efficient solution which could evaluate arbitrary expressions reasonably efficiently without requiring pre-compilation. I needed something which would do basic math with variables, expressions like: "Top+2", "Bottom-2" and "(Right+1-Left)/2".
Research on the Internet turned up a number of fairly good solutions, all of which revolved around creating parse trees (which makes sense). The problem was - they were all rather bulky, and I couldn't afford to add 100K to my applet size just for math. So I started wondering about a linear recursive solution to the problem. The end result is an acceptably performing single class with no external dependencies, weighing in under 10 KiB.
I released an expression evaluator based on Dijkstra's Shunting Yard algorithm, under the terms of the Apache License 2.0:
http://projects.congrace.de/exp4j/index.html