假设二元一次方程如下:
x + y = 11
x - y = 5
解方程如下:
<!DOCTYPE html>
<html lang="zh-CN"> <head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>测试algebra函数库(解两元一次方程)</title>
<script src="js/algebra.min.js"></script>
<script type="text/javascript">
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
//======================================= var x1 = algebra.parse("x+y=11");
var answer1 = x1.solveFor("y");
//console.log("y = " + answer1.toString()); var x2 = algebra.parse("x-y=5");
var answer2 = x2.solveFor("y");
//console.log("y = " + answer2.toString());
//=================================================
//解出X值
var eq = new Equation(answer1, answer2);
console.log("x表达式:" + eq.toString());
var answerX = eq.solveFor("x");
console.log("解出X的值为:" + answerX.toString());
//=================================================
//解出Y值(把x的值代入x1或x2)
eq = x1.eval({
x: answerX
});
console.log("y表达式:" + eq.toString());
var answerY = eq.solveFor("y");
console.log("解出Y的值为:" + answerY.toString()); </script>
</head> <body> </body> </html>
控制台输出:
x表达式:-x + 11 = x - 5
解出X的值为:8
y表达式:y + 8 = 11
解出Y的值为:3
代码写得很粗旷,无任何包装。看得懂就好。