Source:
// Question 12.7
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class q127 extends Applet implements ActionListener
{
private Label lbl;
private TextField txt;
private int num;
private final int PRECISION = 100;
public void init ()
{
lbl = new Label ("Enter value of x");
add (lbl);
txt = new TextField (5);
txt.addActionListener (this);
add (txt);
}
public void paint (Graphics g)
{
double ex1 = 0, ex2 = 0;
ex1 = exp_x (num);
ex2 = Math.pow (Math.E, num);
g.drawString ("The value of e^x using ", 20, 60);
g.drawString ("i) the formula 1 + x + x^2/2! + x^3/3! + ...
is "
+ ex1, 30, 80);
g.drawString ("ii) the value of constant e from the Math
library is "
+ ex2, 30, 100);
}
public void actionPerformed (ActionEvent e)
{
num = Integer.parseInt (txt.getText());
repaint();
}
private double factorial (int number)
{
if (number == 0)
return (1);
else
return number * factorial (number-1);
}
private double exp_x (int x)
{
double val = 1 + x;
for (int i = 2; i <= PRECISION; i++)
val += Math.pow (x, i) / factorial (i);
return val;
}
}