Replacing math expression String for evaluating with Java Script won't replace all ** incidences

StackOverflow https://stackoverflow.com/questions/23371939

I'm trying to parse a math expression in order to evaluate it using .eval.

I coded:

function evaluarExpresion (fx, x) {

    fx = fx.replace("x", x)
    fx = fx.replace("e", "Math.E")
    fx = fx.replace("sin", "Math.sin")
    fx = fx.replace("tan", "Math.tan")
    fx = fx.replace("cos", "Math.cos")
    fx = fx.replace("pi", "Math.PI")
    fx = fx.replace("**", "^")
    return eval(fx)
}

However, when calling with (1^3)/(1+x**(1/2)) for example it will fail as the replaces statement only turn the fx string into:

'(1^3)/(1+x**(1/2))'

So the eval statement throws:

Uncaught SyntaxError: Unexpected token *

How could I fix this or what's a best alternative (any library) for evaluating these such expressions (trigonometrics, sqrt, e, pi, etc) numerically?

有帮助吗?

解决方案 2

You can use the expression parser of math.js, like:

var math = mathjs();

var result = math.eval('(1^3)/(1+x^(1/2))', {x: 16}); // 0.2

One thing: math.js currently lacks bitwise operations as you use in your example. I'm not sure if in your example you actually intend to do bitwise operations or mean to do power operations.

其他提示

You must change your search strings to patterns to use the g (global search) option:

function evaluarExpresion (fx, x) {

    fx = fx.replace(/x/g, x)
    fx = fx.replace(/e/g, "Math.E")
    fx = fx.replace(/sin/g, "Math.sin")
    fx = fx.replace(/tan/g, "Math.tan")
    fx = fx.replace(/cos/g, "Math.cos")
    fx = fx.replace(/pi/g, "Math.PI")
    fx = fx.replace(/\*\*/g, "^")
    return eval(fx)
}

console.log(evaluarExpresion('(1**3)/(1+x**(1/2))' , 9));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top