How to separate long calculation string into usable calculation in Java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Evaluating a math expression given in string form
Sorry about the long (and also slightly strange :)) title, I couldn't think of a better title for it, but here goes.
I have been making a calculator in Java using a JFrame which has JButtons like a real calculator would. As you click the buttons, the calculation appears in a TextArea. When the 'equals' button is pressed, the whole calculation is taken from the TextArea and calculated. The problem I'm having is how to actually calculate the answer. This may sound a little weird, but say the calculation I'm getting is 36+45/22. How would I write the numbers into variables then tell the computer which operations to perform on the variables, and in what order. Can this be done with an infinite number of variables? Is there any way to do this? Thanks for your help.

You could use ScriptEngine:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
System.out.println("result = " + engine.eval("36+45/22"));
Another option is Jep.

Try this, I use a simillar implementation. Works just great. :-D
Evaluate expression in java

If you want to evaluate the expression yourself and not depend on external APIs such as ScriptEngine, you must parse the expression first. This parsing gives you an in-memory representation of the expression which you can then evaluate.
A common way to handle arithmetic expressions is a recursive descent parser. This kind of parser has the nice feature that it evaluates the parsed expression in-place in the parsing methods. An example for a recursive descent parser that does not depend on computer science's formal language theory can be found at http://www.savarese.org/articles/1998-2006/2001-05-Recursive_Descent_Parsing/

Related

How to store mathematical formula in MS SQL Server DB and interpret it using JAVA?

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.

How do i convert a string to double in java when the string contains math functions? [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
i have a string with a math function, like "35+20". i want a new double variable that takes in the result of the math function i.e, 55.0 How do i achieve this? this is actually for android, i'm making a calculator..
Manually parse the string and do a calculation at each operator symbol. It will get more complicated when dealing with brackets, however.
If you want to write it yourself, you'll probably want to implement the Shunting Yard Algorithm.
There are also some libraries that handle it for you.
https://github.com/uklimaschewski/EvalEx
Since you have mentioned you are working on a calculator I am assuming that you might not only be interested in just the + operation but on a bunch of other stuffs too.
You can look in to open source GitHub project linked below which provides the JAVA implementation for the stuff you are trying to do https://github.com/uklimaschewski/EvalEx
which can give you a good set of functionality that you desire.
This project takes in a string as an expression and the returns the result in BigDecimal format.
You can always extend it and tweek it to custom suite you needs.

What language is this (think it's Java?), and how do I test (using a browser ide) the math is correct in it?

div(1, sum(1, exp(sum(div(5, product(100, .1)), -5))))
I'm using this in a Solr query, and want to verify that it is the same as :
Where x is 5.
Is this language Java?
If it is, why am I getting this output here:
http://ideone.com/LWYWtU
If it isn't, what language is this and how do I test it?
Thanks in advance for your help.
EDIT: To add more of the surrounding code, here is the full boost value I'm sending to Solr:
if(exists(query({!frange l=0 u=60 v=product(geodist(),0.621371)})),div(1, sum(1, exp(sum(div(product(5), product(100, .1)), -5)))),0)
The reason I think it might be Java is because in the docs, it says Most Java Math functions are now supported, including: and then lists the math functions I ended up using for code.
Solr is Java, but that's not relevant since this is a set of functions that Solr parses and evaluate itself (and not related to Java, except that the backing functions are implemented in Java).
As far as I can say from what you've mapped the functions correctly, as long as the 5 in product(5) is the same as X. You shouldn't need product there, as the value can be included in div directly as far as I can see.
A way to validate it would be to use debugQuery in Solr and see what the value is evaluated as, and then compare it to your own value. Remember that floating point evaluation can introduce a few uncertanities.

How do I make a mathematical function f(x) for any generic f? [duplicate]

This question already has answers here:
Method for evaluating math expressions in Java
(8 answers)
Closed 9 years ago.
I tried searching for it via google and here but I'm not finding questions to what I mean (search engines don't understand the context by which I mean function).
Essentially I want to do the following
double f(String function, double a){
return function.Function(a);
}
What would happen is the string function is of the form "x^2+2" it would likely be converted somehow to "x.pow(2) + 2" and then x is replaced by a and the result of the function is returned.
Is there any Java class or method that does what I said (or simple way to do it)? Or any code from another source that does what I said or a variant.
I don't have to code what I said, I just need f(x) to solve root finding problems for any function string passed as input. I thought Java would have such a method somewhere but I can't find it.
So, in Java you have an essential problem because you cannot directly convert a String to a mathematical expression. Your options are as follows:
Search for a library that can convert a particularly formatted string to a mathematical expression.
Parse the string yourself. String parsing is difficult and error prone, and the Java around this would be difficult.
Use Scala, which would allow you to directly compose functions to pass into your function, rather than trying to do the expensive conversion from a human-readable string to a machine-interpretable function. Note that Scala is interoperable with Java, but has a bit of a learning curve. Other functional languages can handle this as well, but may lack interoperability.

program for A three-point Gauss integration

I want to write a java program to calculate integral with three-point Gauss.
How to calculate result of every function that is string?
For example want to calculate F(x) = x^4 + cos(x) + e^2x
Evaluating a string is not an easy task by itself.
You have to write your own Interpreter with Lexer and a Parser.
You can consider to use thirdparty libraries for mathematical functions parsing and execution. I've never used any one of them. Simple googling reveals this:
JbcParser
JepParser
I'm sure there are a couple of others around...
Hope this helps

Categories