javascript - Writing a function that "solves" an equation -


i want write function allow me "solve" equation in js.

what want (not in programming language):

function f(x) { 1 + x * x } var z = 2 var y = f(z)  //y 5 number 

what have written in js:

function p(cfg) { .... this.equation = "1 + x"; ....}; p.prototype.eqn = function(x) {     var tmp = eval(this.equation);     return tmp; }; .... p.prototype.draw = function() {.... for(var = 0; < z; i++)     ctx.lineto(i, this.eqn(i)); ....}; 

also i've read using eval in loop not idea, have not figured out way (yet) (js beginner)...

the problem code is, @ least in ff var tmp still contain string this.equation instead of calculated value.

i appreciate further insight much!

thank time :)

edit: because question not formulated well: after execution of line var tmp = eval(this.equation); var tmp hold string equals string this.equation, instead of desired solution y value. not mean solve evaluate, tip :)

based on example, i'd want "evaluate expression", rather "solve equation". evaluating expression, can find many tutorials. i'll break down in brief though. need few steps.

starting string "1 + x * x", need break tokens. specifically, break down into: "1", "+", "x", "*", "x". @ point, can substitute variables ("x") literal values ("2"), giving "1", "+", "2", "*", "2"

now need parse expression. based on order of operations pemdas need create tree data structure, parenthetical clauses (stuff surrounded parenthesis) executed first, multiplication , division next, , additions , subtraction last. parsing not easy task, , may want put simpler bnf grammar (though can find grammar simple math expressions googling).

next, walk tree, depth first, evaluating operations go tree. once top of tree, have solution.

if instead want "solve equation", you're going need more sophisticated, sage


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -