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?


In reply to Computing pi to multiple precision by ambrus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.