/Users/lyon/j4p/src/math/ComputePi.java

1    package math; 
2     
3    /** 
4     * Created by 
5     * User: lyon 
6     * Date: Aug 20, 2003 
7     * Time: 8:19:02 AM 
8     * 
9     */ 
10   public class ComputePi { 
11    
12       static void calculateAndPrintPi() { 
13    
14           double pi = 4.0; 
15           double sliceWidth = 0.5; 
16           double y; 
17    
18           int iterations = 1; 
19    
20           for (; ;) { 
21    
22               double x = 0.0; 
23               while (x < 1.0) { 
24    
25                   y = Math.sqrt(1 - (x * x)); 
26                   pi -= 4 * (sliceWidth * y); 
27                   x += sliceWidth; 
28    
29                   y = Math.sqrt(1 - (x * x)); 
30                   pi += 4 * (sliceWidth * y); 
31                   x += sliceWidth; 
32               } 
33    
34               System.out.println(iterations + ": " + pi); 
35               ++iterations; 
36    
37               sliceWidth /= 2; 
38               if (iterations >20) break; 
39           } 
40       } 
41    
42       public static void main(String[] args) { 
43           calculateAndPrintPi(); 
44       } 
45   } 
46    
47