Just to report, it gets there at $i = 130657.
#!/usr/bin/env perl
use feature qw{ say } ;
use strict ;
use warnings ;
use utf8 ;
# Given that Pi can be estimated using the function
# 4 * (1 – 1/3 + 1/5 – 1/7 + …)
# with more terms giving greater accuracy,
# write a function that calculates Pi
# to an accuracy of 5 decimal places.
my $pi = '3.14159' ;
my $c ;
for my $i ( 0..1_000_000 ) {
my $j = 2 * $i + 1 ;
if ( $i % 2 == 1 ) { $c -= 1 / $j ; }
else { $c += 1 / $j ; }
my $p = 4 * $c ;
my $p2 = sprintf '%.05f' , $p ;
say join ' ' , $i , $pi , $p2 , $p ;
exit if $p2 eq $pi ;
}
No comments:
Post a Comment