admin管理员组文章数量:1415139
suppose I have the following code:
var str = "4*(3)^2/1"
Is the simplest solution just to make a stack of the operators and solve with postfix notation? Or is there a really basic solution I'm missing.
Additionally how can I adapt if I'm using log, ln, sin, cos, and tan?
suppose I have the following code:
var str = "4*(3)^2/1"
Is the simplest solution just to make a stack of the operators and solve with postfix notation? Or is there a really basic solution I'm missing.
Additionally how can I adapt if I'm using log, ln, sin, cos, and tan?
Share Improve this question asked Sep 2, 2017 at 19:49 Jamie AlizadehJamie Alizadeh 1591 silver badge7 bronze badges3 Answers
Reset to default 5Sorry to respond to my own question, but the easiest solution is using math.js
var ans = math.eval(str);
The simplest yet a bit dangerous so you may have to validate (clean) an expression before evaluating is using eval (for exponent-operator ^
, replace it with the exponent-operator in JavaScript **
):
var str="4*(3)^2/1".replace(/\^/g,'**');
console.log(eval(str));
And for special functions such as sin
, cos
, exp
and so on, create a function of your own using the corresponding predefined function in JavaScript:
var str="4*(3)^2/1+(exp(5)*cos(14)^(1/sin(13)))^2".replace(/\^/g,'**');
function sin(x) { return Math.sin(x) }
function cos(x) { return Math.cos(x) }
// so on
function exp(x) { return Math.exp(x) }
console.log(eval(str));
You do not need postfix
notation. You can use eval
method.
var str = "4*(3)^2/1";
console.log(str);
console.log(eval(str));
Also, another solution is using javascript-expression-evaluator which allows you to do stuff like:
Parser.evaluate("2 ^ x", { x: 4 });
本文标签: mathSolve an arithmetic string in javascriptStack Overflow
版权声明:本文标题:math - Solve an arithmetic string in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745218489a2648282.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论