假设二元一次方程如下:
x + y = 11
x - y = 5
解方程如下:
1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 4 <head> 5 <meta charset="UTF-8" /> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> 7 <title>测试algebra函数库(解两元一次方程)</title> 8 <script src="js/algebra.min.js"></script> 9 <script type="text/javascript"> 10 var Fraction = algebra.Fraction; 11 var Expression = algebra.Expression; 12 var Equation = algebra.Equation; 13 //======================================= 14 15 var x1 = algebra.parse("x+y=11"); 16 var answer1 = x1.solveFor("y"); 17 //console.log("y = " + answer1.toString()); 18 19 var x2 = algebra.parse("x-y=5"); 20 var answer2 = x2.solveFor("y"); 21 //console.log("y = " + answer2.toString()); 22 //================================================= 23 //解出X值 24 var eq = new Equation(answer1, answer2); 25 console.log("x表达式:" + eq.toString()); 26 var answerX = eq.solveFor("x"); 27 console.log("解出X的值为:" + answerX.toString()); 28 //================================================= 29 //解出Y值(把x的值代入x1或x2) 30 eq = x1.eval({ 31 x: answerX 32 }); 33 console.log("y表达式:" + eq.toString()); 34 var answerY = eq.solveFor("y"); 35 console.log("解出Y的值为:" + answerY.toString()); 36 37 </script> 38 </head> 39 40 <body> 41 42 </body> 43 44 </html>
控制台输出:
x表达式:-x + 11 = x - 5
解出X的值为:8
y表达式:y + 8 = 11
解出Y的值为:3
代码写得很粗旷,无任何包装。看得懂就好。