All pastes #734224 Raw Edit

MonteCarloPI

public java v1 · immutable
·published 2007-10-12 14:37 UTC
rendered paste body
// Find the value of PI by Monte Carloimport java.util.Random;public class MonteCarloPI {	private long trials=100;	private Random generator = new Random();	public MonteCarloPI( long trials ) { this.trials = trials; }	private int countHits(){		double x, y;		int hits=0;		for(long i=0; i<trials; i++){			x = generator.nextDouble();			y = generator.nextDouble();			if( x*x + y*y < 1 ) hits++;		}		return hits;	}	public double getValue(){ return (4. * countHits() / trials); }	public static void main( String args [] ){		MonteCarloPI PI = new MonteCarloPI(10000000);		System.out.printf("Monte Carlo PI = %.5f\n", PI.getValue());	}}