Kevin's Math Page    
     

Pi Java Applet

This is a Java applet which computes pi using Leibniz's formula.

Here is the source code:

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

public class PiLeibniz extends Applet {

    public void paint(Graphics g)
    {	
   		long	iterations = 0;
   		double	pi = 0.0;
   		double	denom = 1.0;
   		double	value;
   		boolean	addIt = true;
   		
   		while ( iterations < 5000 )
   		{
    		g.clearRect(0, 0, 200, 40);
        	g.drawString("" + pi + "", 10, 10);
        	
        	value = 4.0 / denom;
        	if ( addIt )
        		pi += value;
        	else
        		pi -= value;
        	
        	addIt = ! addIt;
        	denom += 2.0;
        	iterations++;
        }
        
    	g.clearRect(0, 0, 200, 40);
        g.drawString("Pi was computed to " + pi + " after " + iterations + " iterations.", 10, 10);
    }
}

 

 Kevin's Math Page    
Copyright © 1996-2016 Kevin L. Gong