基于代数方程库Algebra.js解二元一次方程功能示例

2017-06-17 jQuery
这篇文章主要介绍了基于代数方程库Algebra.js解二元一次方程功能,结合具体实例形式分析了方程库Algebra.js计算方程的具体使用技巧,需要的朋友可以参考下

本文实例讲述了基于代数方程库Algebra.js解二元一次方程功能。分享给大家供大家参考,具体如下:

假设二元一次方程如下:

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

代码写得很粗旷,无任何包装。看得懂就好。