How can I calculate the value of a mathematical function represented as a string?
For example: f(x,y) = 2*x + 5/y
How can you substitute x and y, then calculate the value of the function,
How can I calculate the value of a mathematical function represented as a string?
For example: f(x,y) = 2*x + 5/y
How can you substitute x and y, then calculate the value of the function,
var f = "f(x,y) = 2*x + 5/y"; var x = 100; var y = 2.5; f = f.replace(/f\(x,y\)\s=\s/g, ""); //удаляем лишнее f = f.replace(/x/g, x); // заменяем подстроку x на значение переменной x f = f.replace(/y/g, y); // тоже самое с y f = eval(f); // вычисляем значение строкового выражения console.log(f); Found an excellent library for solving the problem "math.js":
var f = "2*x^2 + sqrt(5/y)"; var fx = 2; var fy = 5 var node = math.parse(f); console.log(node.eval({x: fx, y: fy})); Source: https://ru.stackoverflow.com/questions/917231/
All Articles