#!/usr/bin/perl use strict; use warnings; # 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 100000000. # 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); $negVal *= -1; $denominator +=2; } 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 100000000\n\n"; print " That is 100 Million please. \n\n"; exit; } unless($num_cycles < 100000001 ) { print " Sorry, your number is too big buddy"; print " \n\n usage: perlpi i \n\n"; print " where i is an integer between 1 and 100000000\n\n"; print " That is 100 Million please. \n\n"; exit; } my $approx_pi = 0; $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";