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.
Related
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?
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.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I am looking into improving my programming skils (actually I try to do my best to suck less each year, as our Jeff Atwood put it), so I was thinking into reading stuff about metaprogramming and self explanatory code.
I am looking for something like an idiot's guide to this (free books for download, online resources). Also I want more than your average wiki page and also something language agnostic or preferably with Java examples.
Do you know of such resources that will allow to efficiently put all of it into practice (I know experience has a lot to say in all of this but i kind of want to build experience avoiding the flow bad decisions - experience - good decisions)?
EDIT:
Something of the likes of this example from the Pragmatic Programmer:
...implement a mini-language to control a simple drawing package... The language consists of single-letter commands. Some commands are followed by a single number. For example, the following input would draw a rectangle:
P 2 # select pen 2
D # pen down
W 2 # draw west 2cm
N 1 # then north 1
E 2 # then east 2
S 1 # then back south
U # pen up
Thank you!
Welcome to the wonderful world of meta-programming :) Meta programming relates actually to many things. I will try to list what comes to my mind:
Macro. The ability to extend the syntax and semantics of a programming language was explored first under the terminology macro. Several languages have constructions which resemble to macro, but the piece of choice is of course Lisp. If you are interested in meta-programming, understanding Lisp and the macro system (and the homoiconic nature of the languge where code and data have the same representation) is definitively a must. If you want a Lisp dialect that runs on the JVM, go for Clojure. A few resources:
Clojure mini language
Beating the Averages (why Lisp is a secret weapon)
There is otherwise plenty of resource about Lisp.
DSL. The ability to extend one language syntax and semantics is now rebranded under the term "DSL". The easiest way to create a DSL is with the interpreter pattern. Then come internal DSL with fluent interface and external DSL (as per Fowler's terminology). Here is a nice video I watched recently:
DSL: what, why, how
The other answers already pointed to resources in this area.
Reflection. Meta-programming is also inseparable form reflection. The ability to reflect on the program structure at run-time is immensely powerful. It's important then to understand what introspection, intercession and reification are. IMHO, reflection permits two broad categories of things: 1. the manipulation of data whose structure is not known at compile time (the structure of the data is then provided at run-time and the program stills works reflectively). 2. powerful programming patterns such as dynamic proxy, factories, etc. Smalltalk is the piece of choice to explore reflection, where everything is reflective. But I think Ruby is also a good candidate for that, with a community that leverage meta programming (but I don't know much about Ruby myself).
Smalltalk: a reflective language
Magritte: a meta driven approach to empower developpers and end-users
There is also a rich literature on reflection.
Annotations. Annotations could be seen as a subset of the reflective capabilities of a language, but I think it deserves its own category. I already answered once what annotations are and how they can be used. Annotations are meta-data that can be processed at compile-time or at run-time. Java has good support for it with the annotation processor tool, the Pluggable Annotation Processing API, and the mirror API.
Byte-code or AST transformation. This can be done at compile-time or at run-time. This is somehow are low-level approach but can also be considered a form of meta-programming (In a sense, it's the same as macro for non-homoiconic language.)
DSL with Groovy (There is an example at the end that shows how you can plug your own AST transformation with annotations).
Conclusion: Meta-programming is the ability for a program to reason about itself or to modify itself. Just like meta stack overflow is the place to ask question about stack overflow itself. Meta-programming is not one specific technique, but rather an ensemble of concepts and techniques.
Several things fall under the umbrella of meta-programming. From your question, you seem more interested in the macro/DSL part. But everything is ultimately related, so the other aspects of meta-programming are also definitively worth looking at.
PS: I know that most of the links I've provided are not tutorials, or introductory articles. These are resources that I like which describe the concept and the advantages of meta-programming, which I think is more interesting
I've mentioned C++ template metaprogramming in my comment above. Let me therefore provide a brief example using C++ template meta-programming. I'm aware that you tagged your question with java, yet this may be insightful. I hope you will be able to understand the C++ code.
Demonstration by example:
Consider the following recursive function, which generates the Fibonacci series (0, 1, 1, 2, 3, 5, 8, 13, ...):
unsigned int fib(unsigned int n)
{
return n >= 2 ? fib(n-2) + fib(n-1) : n;
}
To get an item from the Fibonacci series, you call this function -- e.g. fib(5) --, and it will compute the value and return it to you. Nothing special so far.
But now, in C++ you can re-write this code using templates (somewhat similar to generics in Java) so that the Fibonacci series won't be generated at run-time, but during compile-time:
// fib(n) := fib(n-2) + fib(n-1)
template <unsigned int n>
struct fib // <-- this is the generic version fib<n>
{
static const unsigned int value = fib<n-2>::value + fib<n-1>::value;
};
// fib(0) := 0
template <>
struct fib<0> // <-- this overrides the generic fib<n> for n = 0
{
static const unsigned int value = 0;
};
// fib(1) := 1
template <>
struct fib<1> // <-- this overrides the generic fib<n> for n = 1
{
static const unsigned int value = 1;
};
To get an item from the Fibonacci series using this template, simply retrieve the constant value -- e.g. fib<5>::value.
Conclusion ("What does this have to do with meta-programming?"):
In the template example, it is the C++ compiler that generates the Fibonacci series at compile-time, not your program while it runs. (This is obvious from the fact that in the first example, you call a function, while in the template example, you retrieve a constant value.) You get your Fibonacci numbers without writing a function that computes them! Instead of programming that function, you have programmed the compiler to do something for you that it wasn't explicitly designed for... which is quite remarkable.
This is therefore one form of meta-programming:
Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that
would otherwise be done at runtime.
-- Definition from the Wikipedia article on metaprogramming, emphasis added by me.
(Note also the side-effects in the above template example: As you make the compiler pre-compute your Fibonacci numbers, they need to be stored somewhere. The size of your program's binary will increase proportionally to the highest n that's used in expressions containing the term fib<n>::value. On the upside, you save computation time at run-time.)
From your example, it seems you are talking about domain specific languages (DSLs), specifically, Internal DSLs.
Here is a large list of books about DSL in general (about DSLs like SQL).
Martin Fowler has a book that is a work in progress and is currently online.
Ayende wrote a book about DSLs in boo.
Update: (following comments)
Metaprogramming is about creating programs that control other programs (or their data), sometimes using a DSL. In this respect, batch files and shell scripts can be considered to be metaprogramming as they invoke and control other programs.
The example you have shows a DSL that may be used by a metaprogram to control a painting program.
Tcl started out as a way of making domain-specific languages that didn't suck as they grew in complexity to the point where they needed to get generic programming capabilities. Moreover, it remains very easy to add in your own commands precisely because that's still an important use-case for the language.
If you're wanting an implementation integrated with Java, Jacl is an implementation of Tcl in Java which provides scriptability focussed towards DSLs and also access to access any Java object.
(Metaprogramming is writing programs that write programs. Some languages do it far more than others. To pick up on a few specific cases, Lisp is the classic example of a language that does a lot of metaprogramming; C++ tends to relegate it to templates rather that permitting it at runtime; scripting languages all tend to find metaprogramming easier because their implementations are written to be more flexible that way, though that's just a matter of degree..)
Well, in the Java ecosystem, i think the simplest way to implement a mini-language is to use scripting languages, like Groovy or Ruby (yes, i know, Ruby is not a native citizen of the java ecosystem). Both offer rather good DSL specification mechanism, that will allow you to do that with far more simplicity than the Java language would :
Writing DSL in Groovy
Creating Ruby DSL
There are however pure Java laternatives, but I think they'll be a little harder to implement.
You can have a look at the eclipse modeling project, they've got support for meta-models.
There's a course on Pluralsight about Metaprogramming which might be a good entry point https://app.pluralsight.com/library/courses/understanding-metaprogramming/table-of-contents
I can perfectly see why Clojure is really good for concurrent programming. I can see the advantages of FP also in this regard.
But clearly, not every line of code that we write is part of a thread or needs concurrent access. For those parts of the code (the more simple and sequential piece of code) what is it that Java really missed that Clojure provided?
Were features like Multimethods, Dynamic binding, Destructuring bind really missed in Java?
I supposed my question can also be framed as:
If Clojure did not have the
Concurrency features that it had and
the whole Immutability/Mutability
issue was not of our concern, then
what other features Clojure provides
that would make you use it instead of
Java ?
Were features like Multimethods, Dynamic binding, Destructuring bind really missed in Java?
Yes. Also...
First-class functions. Delicious first-class functions. This isn't just an FP thing. There's a good reason people are clamoring for closures in Java 7.
Code-is-data. This is the benefit of any Lisp. Lisp code isn't just blobs of text you feed into the mouth of a compiler and never see again, it's structures of lists and vectors and symbols and literals that you can manipulate progammatically. This leads to powerful macros and first-class Symbols and lots of other goodies. It leads to a highly extensible and powerful language.
Clojure has better control and looping constructs and the ability to create your own via macros and first-class functions. Java has for and foreach and while (and didn't even have foreach for years). Clojure has map, filter, reduce, mapcat, lots of do forms, lots of if and when forms, list comprehensions via for, and so on. If these didn't exist, you could write them yourself. In Java you get to wait a decade for a committee to (maybe) approve such features.
Minus those dealing with static typing, all of the features set for Java 7, Clojure either already has or could have trivially. "Automatic resource management", Clojure has as with-open. "Language support for collections", Clojure (and Ruby, Perl, Python...) has already. "Strings in switch", Clojure has more powerful case-like constructs like condp, and whatever else you can think up. You could write any of these yourself in a dozen lines of Clojure.
Concise syntax for lists, maps, arrays, sets, sorted sets, sorted maps etc. and nearly interchangeable use of them all thanks to the seq abstraction. Literal support for regexes, characters, anonymous functions, etc.
Java has mandatory checked exceptions, which are annoying; Clojure doesn't.
Java syntax is verbose and irregular. Clojure syntax is concise and regular. Even Java written in Clojure is often more concise than Java written in Java thanks to macros like -> and doto, and constructs like proxy and (soon) reify.
Java code has too much mandatory boilerplate and endless repetition. public static void main(String[] args){...} etc. Clojure has next to none of this boilerplate, while sacrificing little to nothing in terms of expressiveness or power. Even other statically typed languages today seem to be going the way of type inference. There's good reason you need a bulky Java-centric IDE to write and endlessly "refactor" Java code; writing it by hand would drive you insane and wear your fingers down to nubs.
In Java everything is a class or interface, whether it should be or not, which is a cause of unnecessary complexity. There are many programs that have to be mangled beyond recognition to fit into an OOP style. Clojure lets you avoid this. A nice rant to this effect. Clojure focuses largely on verbs.
Interactive programming via REPL is fun. Compile/run/debug cycles are not. Clojure still compiles to .class files if you want it; in the meantime you can sit in the middle of your code and tinker freely while it's running.
Clojure's metadata and sane equality testing are enjoyable to work with. As are its auto-promotion of int to long to Bigint, native handling of rational numbers, and so on.
Dynamic typing leads to shorter, more generic thus more reusable thus more powerful code than static typing. (This is a highly debatable point, obviously, so I put it last.)
The popularity of Scala and Groovy and JRuby and Jython and endless other JVM-languages-that-aren't-Java should be seen as a good indication that while the JVM is good, Java-the-language is unpleasant for many people.
Brian has summarized it really well. Here is something that really impressed me. (From the book Programming Clojure by Stuart Halloway)
Java code, from the Apache Commons:
public class StringUtils {
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
}
Here is a similar implementation in Clojure:
(defn blank? [s] (every? #(Character/isWhitespace %) s))
Well for one there is generally a lot less "ceremony" in Clojure. Languages like Python and Ruby have this advantage over Java as well (thus the popularity of JRuby, Jython).
But note there are times when verbosity cannot be avoided in Java though there might be a clear pattern. Clojure's macros are a huge win here- even over other similarly dynamic languages.
Another thing to consider is that Clojure programs tend to be concurrency safe. So if you decide down the road to make a particular application concurrent, it won't be too painful. Without making alot of decisions up front this will be considerably more difficult with Java.
Also wondering if Clojure would have a clear advantage over Java if it lacked strong concurrency primitives and immutability is kind of like saying, "Well what if Clojure wasn't Clojure?"