Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- String y = "2*y+1";
- int x = y;
- drawgraph(x);
- import javax.script.*;
- interface GraphFunction {
- double eval(double x);
- public static GraphFunction createFromString(String expression) {
- try {
- ScriptEngine engine = new ScriptEngineManager()
- .getEngineByName("JavaScript");
- engine.eval("function graphFunc(x) { return " + expression + "; }");
- final Invocable inv = (Invocable)engine;
- return new GraphFunction() {
- @Override
- public double eval(double x) {
- try {
- return (double)inv.invokeFunction("graphFunc", x);
- } catch (NoSuchMethodException | ScriptException e) {
- throw new RuntimeException(e);
- }
- }
- };
- } catch (ScriptException e) {
- throw new RuntimeException(e);
- }
- }
- }
- class Test {
- public static void main(String[] args) {
- GraphFunction f = GraphFunction.createFromString("2*x+1");
- for (int x = -5; x <= +5; x++) {
- double y = f.eval(x);
- System.out.println(x + " => " + y);
- }
- }
- }
- -5 => -9.0
- -4 => -7.0
- -3 => -5.0
- -2 => -3.0
- -1 => -1.0
- 0 => 1.0
- 1 => 3.0
- 2 => 5.0
- 3 => 7.0
- 4 => 9.0
- 5 => 11.0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement