首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Applet 實現自然常數 e 級數近似計算(誤差 < 0.0001)

     編輯:Java 相關知識

數學原理

e = 1 + 1/1! + 1/2! + 1/3! + ... + 1/n!。當 1/(n+1)! < 0.0001 時截斷,滿足精度要求。

完整 Applet 代碼

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class EApproximationApplet extends Applet implements ActionListener {
    TextField input;
    Button clearBtn;

    public void init() {
        input = new TextField("0", 10);
        clearBtn = new Button("清除");
        add(input); add(clearBtn);
        input.addActionListener(this);
        clearBtn.addActionListener(this);
    }

    public void paint(Graphics g) {
        g.drawString("在文本框輸入 n 後回車", 10, 100);
        g.drawString("顯示 1 + 1/1! + ... + 1/n! 近似值", 10, 120);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == input) {
            try {
                int n = Integer.parseInt(input.getText());
                double sum = 1.0, term = 1.0;
                for (int i = 1; i <= n; i++) {
                    term /= i;      // 遞推計算 1/i!
                    sum += term;
                }
                // 四捨五入到小數點後 4 位
                sum = Math.round(sum * 10000) / 10000.0;
                input.setText(String.valueOf(sum));
            } catch (NumberFormatException ex) {
                input.setText("請輸入整數");
            }
        } else if (e.getSource() == clearBtn) {
            input.setText("0");
        }
    }
}

優化說明

  • 遞推計算 term /= i 避免重複階乘,效率 O(n)。
  • Math.round(x * 10000) / 10000.0 實現四捨五入保留 4 位小數。
  • 異常捕獲防止非數字輸入崩潰。

部署

編譯後配合 HTML <applet code="EApproximationApplet.class" width=300 height=200></applet> 在瀏覽器或 appletviewer 中運行。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved