Cookie Notice

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

2015/07/11

Interview-Style Coding Problem: Estimate Pi

Saw this as an example of the kind of programming test you get in interviews, so I decided to give it a try.

Just to report, it gets there at $i = 130657.

  1. #!/usr/bin/env perl  
  2.   
  3. use feature qw{ say  } ;  
  4. use strict ;  
  5. use warnings ;  
  6. use utf8 ;  
  7.   
  8. # Given that Pi can be estimated using the function   
  9. #   4 * (1 – 1/3 + 1/5 – 1/7 + …)   
  10. # with more terms giving greater accuracy,   
  11. # write a function that calculates Pi   
  12. # to an accuracy of 5 decimal places.  
  13.   
  14. my $pi = '3.14159' ;  
  15.   
  16. my $c ;  
  17. for my $i ( 0..1_000_000 ) {  
  18.     my $j = 2 * $i + 1 ;  
  19.     if ( $i % 2 == 1 ) { $c -= 1 / $j  ; }  
  20.     else { $c += 1 / $j ; }  
  21.     my $p = 4 * $c ;  
  22.     my $p2 = sprintf '%.05f' , $p ;  
  23.     say join ' ' , $i , $pi , $p2 , $p  ;  
  24.     exit if $p2 eq $pi ;  
  25.     }  

No comments:

Post a Comment