0

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.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Jaime
  • 73
  • 5

1 Answers1

1

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.
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102