JavaScript學習:使用Maclaurin級數求天然對數底e的近似值

1、計算原理

Maclaurin級數求以e爲底數的指數函數的公式以下:css

注:公式摘自維基百科頁面html

https://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions瀏覽器

根據該公式可知,當x爲1時,使用「1+1+1/2!+1/3!+... 」的方法能夠求出e的近似值函數

2、頁面代碼

創建一個文件calc_e.html,裏面輸入下面代碼:學習

<html>
  <head>
    <title>JS學習 - 計算天然對數e</title>
  </head>
  <style type="text/css">
      table
      {
          border-spacing: 0 0;
          border-collapse: collapse;
          font-size: 10pt;
      }
      table th
      {
          background: #3399FF;
          text-align: center;
          text-decoration: none;
          font-weight: normal;
          padding: 3px 6px 3px 6px;
          width:200px;
      }
      table td
      {
          vertical-align: top;
          text-align: center;
          padding: 3px 6px 3px 6px;
          margin: 0px;
          border: 1px solid #3399FF;
      }
  </style>
  <body>
    請輸入迭代次數(1-15)
    <input type="text" id="iter_times" onkeydown="keydown();" />
    <input type="button" id="calc_e" value="計算天然對數e" onclick="calculateE();" />
    <hr>
    <table id="result">
      <tr>
        <th>序號</th>
        <th>計算結果</th>
        <th>精確結果</th>
      </tr>
    </table>
    <script>
      //計算天然對數並將結果顯示在table中
      function calculateE()
      {
          //判斷:輸入必須爲正整數且須在1-15之間
          var iterTimes = document.getElementById("iter_times").value;
          if (iterTimes.trim() == "") {
              alert("未輸入任何數據");
              return;
          } else if (!/^\d+$/.test(iterTimes)) { 
              alert("[" + iterTimes + "]不是一個正整數");
              return;
          } else if (iterTimes == 0 || iterTimes > 15) {
              alert("請輸入介於1-15之間的正整數");
              return;
          }

          var table = document.getElementById("result");
          //清空table
          while (table.rows.length > 1) {
            table.deleteRow(1);
          }
          //計算天然對數
          var result = 1;
          var tmp = 1;
          for (var i = 1; i <= iterTimes; i++) {
              var root = table.insertRow(table.rows.length);
              var c1 = root.insertCell(0);
              c1.innerHTML = i;
              var c2 = root.insertCell(1);
              result += 1 / tmp;
              tmp *= (i + 1);
              c2.innerHTML = result;
              var c3 = root.insertCell(2);
              c3.innerHTML = Math.E;
          }
      }
      //在文本框輸入完畢後按下回車視同單擊按鈕
      function keydown() {
          if (event.keyCode == 13) {
              var button = document.getElementById("calc_e");
              button.click();
          } 
      }
    </script>
  </body>
</html>

3、效果演示

使用Firefox瀏覽器(版本號44.0)打開calc_e.html後,效果以下圖所示:spa

ENDcode

相關文章
相關標籤/搜索