Set the variable value as an equation

Asked

Viewed 50 times

0

I wanted an equation to appear as a function of x and not the value of the equation, is it possible? I found nothing, and I’m starting now programming in javascript and do not know much

  • That would be it (basic example) var x = "1+2*3"; console.log(x); console.log(eval(x));?

  • Good afternoon, the answer solved your problem?

1 answer

1

If I understand correctly, you want to save a mathematical equation and run it only when it’s interesting?

A simple example would be to use eval();:

var x = "1 + 2 * 3";
var y = eval(x);

console.log(x, "=", y); // Exibe no console 1 + 2 * 3 = 9

Of course many will talk, Eval is bad and you can really pass anything on Val, which can be a problem, in this case you can use libraries for this:

  • http://mathjs.org - example:

    math.eval('sqrt(3^2 + 4^2)');           // 5
    math.eval('sqrt(-4)');                  // 2i
    math.eval('2 inch to cm');              // 5.08 cm
    math.eval('cos(45 deg)');               // 0.7071067811865476
    
  • https://github.com/silentmatt/js-expression-eval/tree/master - example:

    Parser.parse("2 * x + 1");
    

    Commands:

    • sen(x) - sine x (x is in radians)
    • cos(x) - co-sine x (x is in radians)
    • tan(x) - Tangent of x (x is ... well, you know)
    • asin(x) - arc of sine x (in radians)
    • acos(x) - arc of co-sine x (in radians)
    • atan(x) - Tangent arc of x (in radians)
    • sinh(x) - Hyperbolic sine x (x is in radians)
    • cosh(x) - hyperbolic co-sine x (x is in radians)
    • tanh(x) - Hyperbolic x tangent (x is ... well, you know,)
    • asinh(x) - Arc-sine hyperbolic x (in radians)
    • acosh(x) - hyperbolic arc co-sine x (in radians)
    • atanh(x) - Hyperbolic tangent arc x (in radians)
    • sqrt(x) - Square root of x. The result is Nan (Not a Number) if x is negative.
    • log(x) - Natural logarithm of x (do not base-10).
    • abs(x) - Absolute value (magnatude) of x
    • ceil(x) - Ceiling x - the smallest integer that is > = x.
    • floor(x) - Pavement x - the largest integer which is <= x.
    • round(x) - X is rounded to the nearest integer using "gradeschool rounding".
    • trunc(x) - an integral part of an X, it seems - andar(x) -minus for negative number.
    • exp(x) - ex (exponential function / antilogarithm based on e) predefined functions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.