Domanda

So I have a polynomial equation equivalent in js in a string which I can eval. (assuming the eval execution is safe) for example

2 * x + 3 * y - z = 0;

The above is a string and with appropriate scope where x, y and z are defined, I can eval the above string and it will give me the result. I want to make it so that I can find the value of x where others are given. So my desired output would be.

x = (z - 3 * y) / 2;

Is it possible to get the above string? if not then is it possible to just find the value of x when y and z are given? I know this sounds like homework but it isn't.

È stato utile?

Soluzione

var x, y, z, r1, r2, a, b,
    eq = "2 * x + 3 * y - z = 0;";

console.clear();
eq = eq.replace(" = 0;", "");
y = 12; z = 34;
x = 1; r1 = eval(eq);
x = 2; r2 = eval(eq);
a = r2 - r1; b = r1 - a; x = -b / a;
console.log(x);

Or, if you need the solution formula as a string:

var eq = "2 * x + 3 * y - z = 0;", eq2,
    match, a, b, c, x, y, z;

function process(prefix) {
    prefix = prefix.replace(/[\s\*]/g, "");
    switch (prefix) {
        case "" : return +1;
        case "+": return +1;
        case "-": return -1;
        default : return +prefix;
    }
}

console.clear();
match = eq.match(/^([^x]*)x([^y]*)y([^z]*)z ?= ?0;$/);
if (match === null || match.length !== 4)
    console.log("Invalid equation");
else {
    a = process(match[1]);
    b = process(match[2]);
    c = process(match[3]);
    eq2 = "(" + (-b) + " * y + " + (-c) + " * z) / " + a; 
    console.log(eq2);
    y = 12; z = 34;
    x = eval(eq2);
    console.log(x);
}

eq2 will be (-3 * y + 1 * z) / 2

Altri suggerimenti

If I have understood your question correctly,

To find the value of x:

Evaluate the remaining expression, change its sign, and divide it by x's coefficient (if it's not zero).

To get the string array,

Change the sign of each of the remaining coefficients and divide each by x's coefficient.

EDIT: As already suggested,

say b = exp(0,y,z), a = exp(1,0,0).
x = -b/a
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top