Cookie Notice

As far as I know, and as far as I remember, nothing in this page does anything with Cookies.

2017/03/14

Coding for Pi Day

Today is Pi Day, which is a good day to talk about Pi.

Normally, I'd probably use Pi, sine and cosine to draw things, but instead, I flashed on a couple ways to estimate Pi.

Also, showing you can use Unicode characters in Perl.

  1. #!/usr/bin/env perl  
  2.   
  3. use feature qw{ say } ;  
  4. use strict ;  
  5. use warnings ;  
  6. use utf8 ;  
  7.   
  8. my $π = 3.14159 ;  
  9.   
  10. my $est2  = estimate_2() ;  
  11. my $diff2 = sprintf '%.5f',abs $π - $est2 ;  
  12. say qq{Estimate 2: $est2 - off by $diff2} ;  
  13.   
  14. my $est1  = estimate_1() ;  
  15. my $diff1 = sprintf '%.5f',abs $π - $est1 ;  
  16. say qq{Estimate 1: $est1 - off by $diff1} ;  
  17.   
  18. exit ;  
  19.   
  20. # concept here is that the area of a circle = π * rsquared  
  21. # if r == 1, area = π. If we just take the part of the circle  
  22. # where x and y are positive, that'll be π/4. So, take a random  
  23. # point between 0,0 and 1,1 see if the distance between it and   
  24. # 0,0 is < 1. If so, we increment, and the count / the number  
  25. # so far is an estimate of π.  
  26.   
  27. # because randomness, this will change each time you run it  
  28.   
  29. sub estimate_1 {  
  30.     srand ;  
  31.     my $inside = 0.0 ;  
  32.     my $pi ;  
  33.     for my $i ( 1 .. 1_000_000 ) {  
  34.         my $x = rand ;  
  35.         my $y = rand ;  
  36.         $inside++ if $x * $x + $y * $y < 1.0 ;  
  37.         $pi = sprintf '%.5f', 4 * $inside / $i ;  
  38.         }  
  39.     return $pi ;  
  40.     }  
  41.   
  42. # concept here is that π can be estimated by 4 ( 1 - 1/3 + 1/5 - 1/7 ...)  
  43. # so we get closer the further we go  
  44. sub estimate_2 {  
  45.     my $pi = 0;  
  46.     my $c  = 0;  
  47.     for my $i ( 0 .. 1_000_000 ) {  
  48.         my $j = 2 * $i + 1 ;  
  49.         if ( $i % 2 == 1 ) { $c -= 1 / $j ; }  
  50.         else               { $c += 1 / $j ; }  
  51.         $pi = sprintf '%.5f', 4 * $c ;  
  52.         }  
  53.     return $pi ;  
  54.     }