CSC352: Computing Pi in Parallel with Java

From dftwiki3
Revision as of 12:29, 2 September 2013 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- =Computing an Approximation of Pi: Serial Version: = <br /> <source lang="java"> package DT; // D. Thiebaut // CSC352 Examples // Computation of Pi. This versio...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 13:29, 2 September 2013 (EDT)


Computing an Approximation of Pi: Serial Version:


package DT;
// D. Thiebaut
// CSC352 Examples
// Computation of Pi.  This version is serial and takes a number of iterations to go 
// through from the command line and sums up terms to yield an approximation of Pi.
// To compile and run
//     javac PiSerial
//     mkdir DT
//     mv PiSerial.class DT
//     java DT/PiSerial 100000
//     100000 iterations.  Result = 3.1416026535731527
// 
// To time the execution:
//     time java DT/PiSerial 100000
//     100000 iterations.  Result = 3.1416026535731527
//     real	0m0.238s
//     user	0m0.290s
//     sys	0m0.051s

public class PiSerial {
	
	private static double f( double x ) {
		return 4.0 / ( 1 + x*x );
	}
	
	public static void main( String[] args ) {
	
		//--- syntax: java -jar PiSerial.jar N ---
		if ( args.length == 0 ) {
			System.out.println( "Syntax: PiSerial N\nwhere N is the number of iterations\n\n" );
			return;
		}
		
		int N = Integer.parseInt( args[0] );
		if ( N==0 ) N = 1000;
		
		double sum = 0;
		double deltaX = 1.0/N;
		
		//--- iterate ---
		for ( int i=0; i<N; i++ ) 
			sum += f( i * deltaX );
		
		System.out.println( N + " iterations.  Result = " + sum*deltaX + "\n\n" );
	}
}