regex - Convert functions of math to functions of javascript in java -
i have made string mathematical expression parser follows:
public class expsolver { public string solve(string s){ try { scriptenginemanager mgr = new scriptenginemanager(); scriptengine engine = mgr.getenginebyname("javascript"); return engine.eval(s).tostring(); } catch (scriptexception ex) { logger.getlogger(expsolver.class.getname()).log(level.severe, null, ex); } return "0"; } public static void main(string args[]){ system.out.println(new expsolver().solve(new java.util.scanner(system.in).nextline())); } }
now want add codes parse mathematical functions such sin, cos, tan, ^ (power), log etc. program. best , code efficient solution that? have seen regex expressions unable on such large scale.
how using expression parser of math.js , use via java scriptengine?
here example:
package org.mathjs; import java.io.ioexception; import java.io.inputstreamreader; import java.net.malformedurlexception; import java.net.url; import javax.script.scriptengine; import javax.script.scriptenginemanager; import javax.script.scriptexception; public class mathjsdemo { protected static string mathjs_url = "http://cdnjs.cloudflare.com/ajax/libs/mathjs/1.0.1/math.js"; protected scriptengine engine; public mathjsdemo() throws malformedurlexception, scriptexception, ioexception { scriptenginemanager manager = new scriptenginemanager (); engine = manager.getenginebyname ("js"); engine.eval(new inputstreamreader(new url(mathjs_url).openstream())); engine.eval("var parser = math.parser();"); engine.eval("var precision = 14;"); } public string eval (string expr) throws scriptexception { string script = "math.format(parser.eval('" + expr + "'), precision);"; return (string) engine.eval(script); } public static void main(string[] args) throws scriptexception, malformedurlexception, ioexception { mathjsurl math = new mathjsdemo(); system.out.println(math.eval("a = 4.5")); system.out.println(math.eval("1.2 * (2 + a)")); system.out.println(math.eval("5.08 cm in inch")); system.out.println(math.eval("sin(45 deg) ^ 2")); system.out.println(math.eval("9 / 3 + 2i")); system.out.println(math.eval("det([-1, 2; 3, 1])")); } }
Comments
Post a Comment