This post shows two different ways to compute pi to multiple precision efficiently using elementary arithmetic and square root. We're using the Math::BigFloat library for the multiple precision arithmetic.

Math::BigFloat already has an implementation of pi computation built in of course, but I'd like to show how to write our own.

`#!perl
use warnings; use strict; use 5.010;
use Math::BigFloat try => "GMP";
my $digits = int($ARGV[0] // 0) || 60;
{
say "Newton iteration, using Taylor series of sine and cosine.";
my $b = Math::BigFloat->new(0, undef, -$digits);
my $x = $b + 0.5;
my %x;
while (!$x{$x}++) {
my $m = 1;
my $s = 0;
my $c = 1;
my $k = 0;
while (0 != $m) {
$s += $m = $m * $x / ++$k;
$c += $m = -$m * $x / ++$k;
}
$x += (0.5 - $s) / $c;
}
say "pi = ", 6*$x, ";";
}
{
say "Using Taylor series of arctangent.";
my $b = Math::BigFloat->new(0, undef, -$digits);
my $x = 2 - sqrt($b + 3);
my $f = -$x * $x;
my $m = $x * ($b + 12);
my $a = $m;
my $k = 1;
while (0 != $m) {
$m *= $f;
$k += 2;
$a += $m / $k;
}
say "pi = ", $a, ";";
}
__END__
`

Example output:

`Newton iteration, using Taylor series of sine and cosine.
pi = 3.141592653589793238462643383279502884197169399375105820974942;
Using Taylor series of arctangent.
pi = 3.141592653589793238462643383279502884197169399375105820974945;
`

**Update:** have I mentioned that this post is partly based on this mailing list post I wrote?

Comment onComputing pi to multiple precisionSelectorDownloadCode