#!/usr/bin/perl -w use strict; # # Find an approximate value for Pi using the Pythagorean theorem # # # Start with circle inscribed in polygon # my @circle_in_gon_pi; sub b_from_a (\$) { my (\$a) = @_; my \$b = sqrt((1.0/(\$a*\$a))+1.0) - (1.0/\$a); return \$b; } print "**************** Circle inscribed in polygon ****************\n"; my \$start_b = 1.0; my \$sides = 4; my \$b = \$start_b; foreach my \$i (1..20) { my \$pi_approx = \$b * \$sides; push @circle_in_gon_pi, \$pi_approx; print "Sides: \$sides; side length/2: \$b; pi: \$pi_approx\n"; \$b = b_from_a (\$b); \$sides *= 2; } print "**************** Polygon inscribed in circle ****************\n"; my @gon_in_circle_pi; sub b_from_a_inside (\$) { my (\$a) = @_; my \$b = sqrt((1.0 - sqrt(1.0 - (\$a*\$a)))/2.0); return \$b; } \$start_b = sqrt(2.0)/2.0; \$sides = 4; \$b = \$start_b; foreach my \$i (1..20) { my \$pi_approx = \$b * \$sides; push @gon_in_circle_pi, \$pi_approx; print "Sides: \$sides; side length/2: \$b; pi: \$pi_approx\n"; \$b = b_from_a_inside (\$b); \$sides *= 2; } print "**************** Averages and bounds at each step ****************\n"; print "Format: sides, interior estimate, exterior estimate, average of them\n"; print "Each entry is formatted as a table line.\n"; my \$low = 0.0; my \$high = 5.0; my \$best = 0; \$sides = 4; foreach my \$i (0..20) { my \$new_high = \$circle_in_gon_pi[\$i]; my \$new_low = \$gon_in_circle_pi[\$i]; my \$out_of_range = 0; if (\$new_low < \$low || \$new_low > \$high) { print "Low value for step \$i out of range: \$new_low\n"; \$out_of_range = 1; } if (\$new_high < \$low || \$new_high > \$high) { print "High value for step \$i out of range: \$new_high\n"; \$out_of_range = 1; } my \$average = (\$new_low + \$new_high) / 2.0; print "\n"; print "\$sides \$new_low \$new_high \$average\n"; print "\n"; ##print "Step: \$i; Sides: \$sides; Low: \$new_low; High: \$new_high; Average: \$average\n"; if (\$out_of_range) { last; } \$best = \$average; \$low = \$new_low; \$high = \$new_high; \$sides *= 2; } my \$pi = 4.0 * atan2(1,1); print "pi, by taking 4*arctan(1): \$pi\n"; my \$error = \$best - \$pi; if (\$error < 0) { \$error *= -1.0; } print " Error: \$error\n";