This is a perlified conflation of a nice algorithm stolen from the web.
#!/usr/bin/perl
use strict;
use Math::BigFloat qw(:constant);
$|++;
my $epochs = 100;
my $begin = time;
print 'PI:', &calc_pi( $epochs ), "\n"
, '(', time - $begin, " sec)\n";
sub calc_pi
{
my $iter = shift;
return 16 * &ataninvint( 5,$iter)
- 4 * &ataninvint(239,$iter);
}
sub ataninvint
{
my ($x, $iter) = @_;
my $res = Math::BigFloat->new(1) / $x;
my $term = Math::BigFloat->new($res);
my $x2 = $x * $x;
my $div = 1;
$res += -Math::BigFloat->new($term /= $x2)/($div += 2)
+Math::BigFloat->new($term /= $x2)/($div += 2)
for 1..$iter;
return $res;
}
UPDATE:
here are lots of ways to calculate pi