1 Reply Latest reply: Nov 6, 2010 10:17 AM by baftos RSS

    Parsing a maths equation into a double

    804633
      Basically i need to change an equation (represented by a String) into a number.

      I know how to change a String into a double using Double.parseDouble(String); method.

      I was wondering if there is a method (like above) that can change an equation like "y=A+B*cos(a*x+b)+C" instantly into a Double? (obviously the variables would be doubles eg: "y=1.2+3*sin(3*1.2+-5.6)+6").

      At the moment, I have text fields for A,B,a,b,C, and a list for the cos/sin/tan/etc functions. But the user would like to just type in a mathematical function and perform the necessary calculations.

      Thanks in advance.

      James
        • 1. Re: Parsing a maths equation into a double
          baftos
          You may want to take a look at :
          ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
          engine.eval("1+2+3");
          I know this works, but I don't know if JavaScript syntax is good for you and how much mathematical power is there in Javascript.
          The embedded Javascript is also able to call back into Java for more math power.

          Edit:
          This program
          import javax.script.*;
          
          public class X {
               public static void main(String[] args) throws Exception
               {
                    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
                    System.out.println(engine.eval(args[0]));
               }
          }
          produces this output:
          C:\temp>java X java.lang.Math.abs(-25.3)
          25.3
          
          C:\temp>java X java.lang.Math.sin(25.3)
          0.16648000353715925
          
          C:\temp>
          Edited by: baftos on Nov 6, 2010 11:15 AM