All pastes #745508 Raw Edit

Unnamed

public text v1 · immutable
·published 2007-10-22 13:28 UTC
rendered paste body
/* 
 * r = radius = 1
 * A_Circle = r^2 * Pi = r * r
 * A_Square = (2*r)^2 = 4 * r * r
 * X_C_S = A_Circle / A_Square
 * Y_C_S = InCircleCount / SampleCount
 * X_C_Y = Y_C_S
 * InCircleCount / SampleCount = Pi * 1/4 <=>
 * Pi = 4 * InCircleCount / SampleCount 
 */

public class Pi {

	private static double THRESHOLD=0.000001f;

	private static double root(double x){
		if(x < 0) return -1.0f;
		double t0,t1;
		t0=1.0f;
		do{
			t1=t0;
			t0=(t1 + x/t1)/2.0f;
		}while(Math.abs(t0 - t1) >=  THRESHOLD);
		return t0;
	}
  
	private static float calc(int steps){
		int c = 0;
		double x,y;
		for(int i = 0; i<steps; i++){
			x = Math.random();
			y = Math.random();
			if(root(x * x + y * y) <= 1){
				c++;
			}
		}
		return 4.0f * c / steps;		
	}

	public static void main(String args[]){

		System.out.print("Pi = " + calc(1000000));
	}

}