Universe - 2 months ago 7x

Java Question

I working on a small Application that I want to get a mathematical function, and range of x (a,b) and display the graph of it.

In some point I call a method that execute the function for a x.

I'm stack on point that I get the function (ex. f(x)= 2*x+1 ) from TextField and use it as Java code

let's say:

`class Myclass extends JFrame{`

blah blah ...

JLabel lblFx =new JLebel("f(x=)");

JTextfield Fx = new JTextField();

//and lets say that this method calculate the f(x).

//get as argument the x

double calculateFx(double x){

return 2*x+1; // !!!!BUT HERE I WANT TO GET THIS 2*x+1 FROM TextField!!!!!

}

}

Any idea?

Answer

I found this awesome Expr lib!

"This package parses and evaluates mathematical expressions over floating-point numbers, like 2 + 2 or cos(x/(2*pi)) * cos(y/(2*pi)).

The design priorities were ease of use with helpful error messages, ease of integration into applets, and good performance: fast evaluation and short download times. Features and flexibility were not high priorities, but the code is simple enough that it shouldn't be hard to change to your taste."

In my example

```
class Myclass extends JFrame{
blah blah ...
JLabel lblFx =new JLebel("f(x=)");
JTextfield Fx = new JTextField();
String formula = Fx.getText();//2*x+1 OR cos(x) OR lot of other functions
//and lets say that this method calculate the f(x).
//get as argument the x
double calculateFx(double x){
// The Expr Object that will representing the mathematical expression
Expr expr = null;
try {
// parsing function formula to mathematical expression
expr = Parser.parse(formula);
} catch (SyntaxException e) {
System.err.println(e.explain());
return;
}
// Define(make) what will be the variable in the formula, here x
Variable vx = Variable.make("x");
// Set the given value(x) in variable
vx.setValue(x);
//return (mathematical) expression's value. See more for Expr lib how work...
return expr.value();//
}
}
```

finally when somewhere in your project call `calculateFx(x)`

, for a given x, you will get the f(x) value!

Source (Stackoverflow)

Comments