1

Possible Duplicate:
free Java library for evaluating math expressions

I was wondering if there's a package in Java that can take in a string, say "x^2+e^x*cos(x)", and evaluate it as a mathematical function given a value of x like a calculator would -- ideally one that's free and publicly available. Does this exist?

Community
  • 1
  • 1
NcAdams
  • 2,521
  • 4
  • 21
  • 32
  • This may help: http://stackoverflow.com/questions/3587557/good-symbolic-math-cas-library-for-jav – Abhinav Sarkar Sep 06 '12 at 03:55
  • http://stackoverflow.com/questions/3422673/java-evaluate-string-to-math-expression - this too google: java string math – tehdoommarine Sep 06 '12 at 03:55
  • One way is to use the [`ScriptEngine`](http://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngine.html). See [this answer](http://stackoverflow.com/questions/7441625/how-to-find-a-button-source-in-awt-calculator-homework/7441804#7441804) for an example. @Thilo notes *"I'd be careful with ScriptEngine if direct user input is involved, though. A tailored math library might be better."* – Andrew Thompson Sep 06 '12 at 04:01

1 Answers1

0

There are lots - It's a fairly simple and common parser-writing exercise so lots of people have had a go and published some code. See e.g.:

The likely issue will be the range of mathematical functions available. You can expect the standard ones, but may need to customise / add your own for the more unusual functions (cosh perhaps?)

Another option is to embed a language interpreter, e.g. Groovy to do the calculations. This is a bit more heavyweight and means that you will need to be much more conscious of security risks (e.g. if the code might get run on a server) but could make sense if you have a more general need for scripting.

mikera
  • 105,238
  • 25
  • 256
  • 415