Create your blog and photo album with postbit
Create your blog and photo album

Create new post

Content:

Upload a picture:
Tags (keywords separated by comma)

Save Cancel
perl:   Followers: 2 ; Following: 2

Explore perl's photo albums:
Perl images (1)
Photos from posts (2)

Perl script to calculate PI number using Bellard's Algorithm


This is a fast way to calculate PI with Perl. It uses Bellard's PI calculation algorithm. It's a simple PERL implementation of Bellard's method.

#!/usr/bin/perl

# Fabrice Bellard's Algorithm to calculate number PI using PERL.
# Perl Script by Rodrigo Siqueira
 
# Run this to calculate PI with 1000 decimal places:
# perl -Mbignum=p,-1000 pi-bellard.pl
 
use bignum;
 
my $pi;
 
for my $k (0..340) {
  $pi += (1/2**6) * ((-1)**$k/(1024**$k)) * ( - (32)/(4*$k+1) - (1)/(4*$k+3) + (256)/(10*$k+1) - (64)/(10*$k+3) - (4)/(10*$k+5) - (4)/(10*$k+7) + 1/(10*$k+9) );
}
 
print "PI=".$pi;
 
### END ###
 
Result:

PI=3.
1415926535 8979323846 2643383279 5028841971 6939937510 5820974944 5923078164 0628620899 8628034825 3421170679
8214808651 3282306647 0938446095 5058223172 5359408128 4811174502 8410270193 8521105559 6446229489 5493038196
4428810975 6659334461 2847564823 3786783165 2712019091 4564856692 3460348610 4543266482 1339360726 0249141273
7245870066 0631558817 4881520920 9628292540 9171536436 7892590360 0113305305 4882046652 1384146951 9415116094
3305727036 5759591953 0921861173 8193261179 3105118548 0744623799 6274956735 1885752724 8912279381 8301194912
9833673362 4406566430 8602139494 6395224737 1907021798 6094370277 0539217176 2931767523 8467481846 7669405132
0005681271 4526356082 7785771342 7577896091 7363717872 1468440901 2249534301 4654958537 1050792279 6892589235
4201995611 2129021960 8640344181 5981362977 4771309960 5187072113 4999999837 2978049951 0597317328 1609631859
5024459455 3469083026 4252230825 3344685035 2619311881 7101000313 7838752886 5875332083 8142061717 7669147303
5982534904 2875546873 1159562863 8823537875 9375195778 1857780532 1712268066 1300192787 6611195909 2164201981
 
Warning: The last digit should be "9", not "1", it happens because of a round error in the last digit. So the last 10 digits (from digit place 990 to 1000) should be 2164201989.
 
The format 10 in 10 digital places can be obtained by using this format:
$pi =~ s/^3.//; # Remove "3." from the beginning.
$pi =~ s/(\d{100})/$1\n/g; # Add enter each 100 digital places of PI
$pi =~ s/(\d{10})/$1 /g; # Add space to each 10 digital places of PI
print "PI=3.$pi";
 
 
If you want to calculate PI with more than 1000 places using this script, you need also change max $k from 340 to a larger number.

Post by perl (2014-12-17 17:36)

Post your comment:

Name: Email: Site:




| Explore users | New posts | Create your blog | Create your photo album |
| About Postbit | Our blog | Terms of use | Contact Postbit |


Copyright © 2017 - postbit.com