#!/usr/bin/perl use strict; use warnings; # Script created for calculating e. # Uses the Euler series. # e = infinite sum 0 to infinity 1/n! # # e = 1 + 1/1! + 1/2! + 1/3! ... # # # Author: Victor Odlivak August 3, 2007 # # input: an integer stating number of iterations desired for # converging e series. # # output: Approximation for e to desired number of iterations of # series. # # usage perlR_e i # where i is an integer between 1 and 10000. # sub calc_e { my ($numIterations) = @_ ;# number of iterations of loop to # calculate e. my $numerator = 1; my $denominator = 1;# starting value, this will increment my $calculatedVal = 1;# starting value for zeroth cycle. # Note the e to the zero power the first term is # equal to 1. Anything to the zero power is 1. Also zero! is by # definition 1. my $j = 0; # Number of iterations for loop to calculate e for ($j = 0; $j < $numIterations; $j++) { $calculatedVal += $numerator/(factorial($denominator)); # print "$calculatedVal is current value for iteration $j \n"; $denominator++; # The denominator is incremented by one and we take the factorial. } return $calculatedVal; } sub factorial{ # input value to be factoralized and return it. # It took me over three hours to figure this alorightm out! # Note, this is a non recursive algorithm! # my ($input_val) = @_; my $result = 1;# This is the case for 0! or 1! while ($input_val > 1) # notice the DOUBLE Decrementation here. This is the # gist of it. At first I did it without this and I kept # getting factorials that were way too big. # # Enjoy!! # # You start off with $result of 1. Then you walk the array, # i.e. Factorial(n) = n* (n-1) * (n-2) .... # i.e. for Factorial(6) # $result = 1 * 6 * 5 # $result = 30 * 4 * 3 # $result = 360 * 2 # $result = 720 (done for loop with four iterations # { $result = $result * $input_val * (--$input_val); --$input_val; } return $result; } # Main Program Section my $num_cycles = shift(@ARGV); unless($num_cycles) { print " Sorry, you forgot to enter an iteration number for the "; print " e series. \n\n usage: perl_e i \n\n"; print " where i is an integer between 1 and 1,000\n\n"; exit; } if (($num_cycles > 1000) or ($num_cycles < 1)) { print " Sorry, you entered an iteration number out of range"; print " for the e series. \n\n usage: perl_e i \n\n"; print " where i is an integer between 1 and 1,000\n\n"; exit; } my $approx_e = 0; $approx_e = calc_e ($num_cycles); print "The calculated value of e with $num_cycles"; print " cycles of the calculation loop is: \n"; print " $approx_e \n"; print " Note, the calculation loop starts at the zeroth cycle "; print " which has a value of 1. \n";