replax replax - 2 months ago 5x
Javascript Question

Writing a function that "solves" an equation

I want to write a function which will allow me to "solve" an equation in js.

what I want (not in a programming language):

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

what I 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 i = 0; i < z; i++)
ctx.lineTo(i, this.eqn(i));

also I've read that using eval in a loop is probably not a good idea, but I have not figured out another way (yet) (JS beginner)...

The problem with this code is, that at least in FF the var tmp will STILL contain the string from this.equation instead of the calculated value.

I would appreciate any further insight very much!

Thank you for your time :)

EDIT: because my question was not formulated very well:
after the execution of line
var tmp = eval(this.equation);
the var tmp will hold a STRING which equals the string this.equation, instead of the desired solution y value.
Also I do not mean solve but evaluate, thanks for that tip :)


Based on your example, I'd say that you want to "evaluate an expression", rather than "solve an equation". For evaluating an expression, you can probably find many tutorials. I'll break it down in brief though. You need to do a few steps.

Starting with your string "1 + x * x", you need to break it into tokens. Specifically, break it down into: "1", "+", "x", "*", "x". At this point, you can substitute your variables ("x") for their literal values ("2"), giving you "1", "+", "2", "*", "2"

Now you need to parse the expression. Based on order of operations PEMDAS you need to create a tree data structure, where parenthetical clauses (stuff surrounded by parenthesis) are executed first, multiplication and division next, and then additions and subtraction last. Parsing is often not an easy task, and you may want to put together a simpler BNF grammar (though you can probably find a grammar for simple math expressions with some googling).

Next, walk the tree, depth first, evaluating the operations as you go up the tree. Once you get to the top of the tree, you have your solution.

If instead you want to "solve an equation", you're going to need something much more sophisticated, like Sage