#!/usr/bin/perl use strict; use warnings; use Time::HiRes qw( clock ); # NOTE, the HiRes.pm is automatically there in Linux # but not on the MAC. I could not easily recompile # the Linux version to run on the MAC. # my $clock0 = clock(); # Start clock to monitor CPU time # Start of monitoring for time. # Script created for calculating Pi # Uses the Gregory-Leibniz Series # Found on http://en.wikipedia.org/wiki/Pi#Calculating_.CF.80 # # Author: Mark Stump, Amended by Victor Odlivak July 27, 2007 # # input: an integer stating number of iterations desired for # converging PI series from Leibniz etc. # # PI = 4 +4/3 -4/5 +4/7 etc. # # output: Approximation for PI to desired number of iterations of # series. # # usage perlpi i # where i is an integer between 1 and 10000000. # sub calc_pi { my ($numIterations) = @_ ;# number of iterations of loop to # calculate PI. my $numerator = 4; my $denominator = 1; my $negVal = 1; my $calculatedVal = 0; my $j = 0; # Number of iterations for loop to calculate pi for ($j = 0; $j < $numIterations; $j++) { $calculatedVal += $negVal * ($numerator/$denominator); # Note, numberator is always four. It does not change. $negVal *= -1; #reverse the sign for each iteration telling # whether to add or subtract. $denominator +=2; # The denominator is always two more, than it # was in the term before. } return $calculatedVal; } # Main Program Section my $num_cycles = shift(@ARGV); unless($num_cycles) { print " Sorry, you forgot to enter an iteration number for the "; print " PI series. \n\n usage: perlpi i \n\n"; print " where i is an integer between 1 and 100,000,000\n\n"; exit; } my $approx_pi = 0; print "Starting CPU timer at $clock0 seconds .. be patient please if"; print " you are doing over a million iterations \n"; $approx_pi = calc_pi ($num_cycles); print "The calculated value of pi with $num_cycles"; print " cycles of the calculation loop is: \n"; print " $approx_pi \n"; my $clock1 = clock(); my $clockd = $clock1 - $clock0; print "Finishing time is = $clockd seconds \n";