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);
または、解の式を文字列として必要な場合は、次のようにします。
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
になります(-3 * y + 1 * z) / 2