Implements simple but slow formula pi/4 = 1 -1/3 + 1/5 -1/7 + 1/9 .....
Choose the number of terms to compute (from zero to a billion)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class PiSimple extends Applet implements ActionListener {
TextField tf;
double piOverFour;
int attempts;
Label instructions, colorChange;
public void init()
{
attempts = 0;
instructions = new Label("Type number up to a billion and
click enter");
add(instructions);
tf = new TextField(9);
add(tf);
tf.addActionListener(this);
colorChange = new Label("Color will change when calculation
finished");
add(colorChange);
}
public void paint(Graphics g)
{
g.drawString("Approximation of pi = " + String.valueOf(4.0*piOverFour),
10 , 100);
g.drawString("Actual first dig of pi =
3.14159265358979323846264338....", 10 , 120);
}
static final int getIntFromString(String s)
{
s = s.trim();
if (s.equals("") || s == null) return (1);
try
{
return (Integer.valueOf(s).intValue());
}
catch (Exception e)
{
return(1);
}
}
public void actionPerformed (ActionEvent e)
{
attempts++;
int terms = getIntFromString(tf.getText());
if (terms > 1000000000) terms = 1000000000;
piOverFour = 0.0;
for (int i=0; i<terms; i++)
{// implements formula pi/4 = 1 -1/3 + 1/5 -1/7 + 1/9 .....
if (i%2 == 0) piOverFour +=
1.0/((double)(2*i + 1));
else piOverFour -= 1.0/((double)(2*i
+ 1));
}
Color color = new Color(225, 225 - ((attempts%2)*30), 255);
setBackground(color);
instructions.setBackground(color);
colorChange.setBackground(color);
repaint();
}
} // END OF Class PiSimple