Is there a way to create a function as below?
I need to calculate the area of triangle, and I don't remember the right formula to calculate this and there is no internet or other sources of some information to me. What I do remember is that arguments for such function are some side b and height h. So I want to create some function which would look like this:
public static void calculate(String forgottenFunc, int... params) {/*implementation*/};
I thought of implementing based on JavaScript eval function from Java, withough using RegExp. I've got stuck on converting string (forgottenFunc) to some real function that would use given parametrs to calculate what I need. Or any alternatives on Python's eval or some other feature.
Thanks
Try Jep, a free Java math parser.
mXparser will fit your needs :-) Please follow below example:
import org.mariuszgromada.math.mxparser.*;
...
...
public static double calculate(String forgottenFunc, double... params) {
Function f = new Function(forgottenFunc);
return f.calculate(params);
}
...
...
System.out.println( calculate("p(a,h) = a*h/2", 2, 3) );
Result:
3.0
Please follow mXparser tutorial
Additionally - this software is using mXparser as well - you can learn the syntax Scalar Calculator app
Best regards
Based on your comments, I see that you want a parser, not a closure.
There is no built-in equivalent of the JavaScript eval function. It is considered evil.
You can either use a third party parser like zovegames suggests or build your own using something like javacc.
For a general solution: you could embed MVEL in your program, pass the formula as a string, bind the parameters and evaluate it. From the linked page:
MVEL is a powerful expression language for Java-based applications. It provides a plethora of features and is suited for everything from the smallest property binding and extraction, to full blown scripts.
Related
I am trying to develop an advanced math expression calculator in Java. My goal is that calculator can determinate expressions like these:
2 * 6^( log(123) - sin(7)^cos(2) )
lim( (5x^2) / x , x -> 1)
.
.
.
Is there anything (default function, external library) for this in Java or C++?
You could do this...
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Test {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "2 * 6^( log(123) - sin(7)^cos(2) )";
System.out.println(engine.eval(foo));
}
}
In addition if you want to solve the limits, you could always use an API.
You can send the request with the right syntax for that api, which will give you the
result you can parse. This is however harder to program and API's are often not free.
Another option is calculating limits yourself, I'm not aware of APIs for that or standard
Java functions.
If you really want to start from scratch and re-invent the weel I would suggest you build your own eval function. This is a good starting point for that: Java/c++ example.
If your expressions are not very complex, I think this answer will guide you in the right way:
Built-in method for evaluating math expressions in Java
If your expressions are rather sophisticated, using limits as in your example, I advice you to take a look at the Dragon Book. It should be easier to implement an easy expression parser and use some strong math library below.
This is less of a Java domain question and more of a language parsing problem. The traditional way to approach this is to build a lexer and parser, sometimes in another language, that generates the code in the language you want. This way you separate the parsing concerns from the actual "client" program concerns.
This can be easier, in the long run, than trying to write what is going to be a pretty complicated regular expression state machine that will be hard to prove is correct in all cases. An infix math parser/processor is interesting enough that having a "little language" version of the rules and definitions makes it a lot easier to prove your program is correct.
In Java you might want to consider ANTLR to generate the parser, though I admit I have never had to use it. But my understanding is that ANTLR is familiar enough if you have used Lex & Yacc.
[UPDATE]
I don't know if infix is a hard requirement, but parsing complex math using a stack and postfix operations can be much easier to implement if you don't want to generate a parser. As an added bonus, this allows you to do math like Yoda.
In general, what you need is called a computer algebra system. I don't know what requirements you have but there are at least 2 general ways to go about it.
(1) link your program to a library to do the algebraic stuff. For C++ you can try Yacas and for Python you can try Sympy. Dunno about Java.
(2) write your program separately and talk to a CAS via a socket. In that case the CAS could be anything, e.g., Maxima, Sage, etc etc. A socket interface is maybe less work than you might think -- it is certainly much, much less work than reimplementing CAS functions.
My advice, without knowing your requirements, is to write your program in Python and use Sympy.
I've been searching google for a while now but can't find what I need.
I need an open source mathematical expression parser & evaluator - of which there are a myriad -
But one which links to a decent math library like Apache Commons Math. I need complex arithmetic, basic functions like sin, log that work on complex plane, and functions like gamma, erf.
The closest answer I found was Built-in method for evaluating math expressions in Java - but I couldn't see how, other than writing countless helper functions, to bind
jexpr
jruby
jeval
javax.script
with Commons math. Also it would take quite some work to modify my own existing (real-valued) expression parser to bind all the functions.
Plus, including a whole scripting programming language like python/ruby in my app seems overkill, where what I want to do is barely more than an old-fashioned pocket calculator.
Hasn't someone done this sort of thing already?
Thanks!
You may want to check out an implementation that I created:
https://github.com/uklimaschewski/EvalEx.
It is based on java.math.BigDecimaland supports the basic matehmatical and boolean operations.
It is a very compact implementation: only a single class file without any dependencies to other libraries. Plus, it can be easily extended with custom functions and operators.
Your gamma(1.8) example can be added in this way:
Expression e = new Expression("gamma(1.8)");
e.addFunction(e.new Function("gamma", 1) {
#Override
public BigDecimal eval(List<BigDecimal> parameters) {
BigDecimal gamma = MyMathLibraryGammaCalculation(parameters.get(0));
return gamma;
}
});
e.eval(); // returns gamma(1.8)
We used to do this with ScriptEngine for javascript - Not sure if that is sufficient for your requirements... here is a reference in SA:
Is there an eval() function in Java?
Pascal has a feature of set types. It allows nice constructs like this:
if i in [5..10] then
...
Are there any similar things in Java?
I came up only with this ugly construction that doesn't accept intervals:
if ((new HashSet<Integer>(Arrays.asList(new Integer[]{5,6,7,8,9,10}))).contains(i))
...
Yes you're right. You need an implementation of a Set in Java and have to populate it yourself with a loop if you want a non-sequential list of numbers.
Also, Java does not support the contruct of a Range. Other JVM laguages like Groovy and Scala however do.
This post may add some more colour
Unfortunately, there are no such beautiful construct in Java. But apache-commons provides a Range class which may suite your needs
I am coming from PHP to Java and I have some questions about "dynamic" functions.
Kinda like in php where you can do an include(VARNAME.".php"); and if varname is a it'll include a.php if its x it'll include x.php.
I wanna do that in Java but with functions.
Kinda like I have a varname and I want to include a function. So if varname is Test it'll include test() but I have a bunch of functions and its a nuisance to do
if(varname == "x"){ x(); }.
Is there any easy way to do it?
First off, if(varname == "x") is surely not what you want. This is a common Java mistake and will check the object identity, not the object value. You want if(varname.equals("x")).
Second, this isn't very idiomatic Java. As Jason pointed out, you can use reflection to do a dynamic method look-up. However, there is almost certainly a better design for what you are trying to accomplish.
Java is a very different language from PHP. Trying to apply PHP idioms to Java will only cause you pain and suffering.
Having said all that, I think this is roughly the code you are looking for:
Method method = this.class.getDeclaredMethod("x", new Class[] {});
method.invoke(this, new Object[] {});
If your varname equates to a function on the class you are in, you could theoretically use reflection to accomplish this. See this article from Sun/Oracle for more details
Hello i often develop JTableModels in which some cells must contain the result of apliying a certain simple mathematical formula. This formulas can have:
Operators (+,-,*,/)
Number constants
Other cell references (which contains numbers)
Parameters (numbers with a reference name like "INTEREST_RATE")
I often resolve it making a little calculator class which parses the formula, which syntax i define. The calculator class uses a stack for the calcs, and the syntax uses allways a Polish notation.
But the Polish notation is unnatural for me and for my users. So my question is...
Is there a lib which runs in 1.5 jvm's and can handle my requeriments and use normal notation (with brackets, i don't know the name of this notation style) for formulas?
P.D it's supposed that the formulas are allways syntax correct and i can preprocess the numbers that are not constants to provide their values
Have you thought about the benefits of JSR-223 ? in a few words, this spec allows Java developers to integrate with great ease dynamic languages and their parsers. Using such parser, your need for defining a parser transforms into the need for defining an internal DSL, which resolves into creating simply a good API, and letting your user choose wether they prefer Javascript/Groovy/Scala/WTF syntax they happen to prefer.
Try JEP.
You can define new variables to the parser hence it can contain reference names like "INTEREST_RATE".But you have to define it before hand.
As for cell references you will have to extract the number's and edit the expression accordingly or probably there might be some options which I'm not yet aware of.
If you can't use Java 6 and its scripting support then have a look at the Apache Bean Scripting Framework (BSF). From that page:
... BSF 3.x will run on Java 1.4+, allowing access to JSR-223 scripting for Java 1.4 and Java 1.5.
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
There's a commercial tool called formula4j which may be useful to some.
It has no direct help for cell references. You would have to handle those yourself, and translate the cell references into values.