What do I do in my spare time? Well, I calculate Pi.

March 26, 2007

Hello again.

I’ve been doing a little project for myself. I’m attempting to write a fairly simple program in multiple programming languages and compare them in many ways. I compared the writing in terms of difficulty of writing, amount of overhead, and the time the programs took to run. The program I decided to write was a simple program that would loop and calculate the value of Pi using the Gregory-Leibniz Series. This series (I found it here, thanks wikipedia). I used this way to calculate Pi because it was fairly simple to implement.

I have currently implemented the program in four languages: Ruby, Perl, C, and Java. The line counts for each of the programs is followed (with comments removed) directly from the “wc” command in UNIX. The exact line and output is as follows:

Ophanim:~/picalc/tempPi Gatacoma$ ls
picalc.c picalc.java picalc.pl picalc.rb
Ophanim:~/picalc/tempPi Gatacoma$ wc *
22 80 549 picalc.c
28 97 751 picalc.java
13 52 346 picalc.pl
13 41 248 picalc.rb
76 270 1894 total
Ophanim:~/picalc/tempPi Gatacoma$

The counts go Lines, Words, and Characters (I believe). As I said before, this was with removing the comments I made and also with removed any empty line in the code. Another difference is that the C and Java programs are coded to take a value at the command line, while the Ruby and Perl programs used a hard-coded number.

The variable-parameter is the number of iterations that the program goes though. A higher number is supposed to give a larger and more specific value of Pi. A limitation I’ve found, however, is that I cannot get a very high precision on my numbers. Anyone with an idea on how to get a larger precision on the numbers, I encourage you to speak with me about it.

I’ve chosen to run each of these programs with 100 million iterations. Which is a bunch. And now, the testing.


Ruby is something. I’ve heard many good things about the language, and figured this was a good time to try it out. Ruby is an object-oriented scripting language that has implications far beyond what I’m doing with it. If I have the chance, I’d like to learn more about the language and how to use it.

It should also be noted that Ruby is an interpreted language, and I believe it’s speed suffers due to that. Interpreted means (for those who don’t know) that the language does not have a compiler and that you run the source code directly.

I found the ruby code to be rather easy to learn and implement, with little code that was there as just “Syntactic Sugar”

The source code for this script (commented, spaced) is below:

Edit: I just realized that the wordpress editor kinda ate my tabbing. My bad.

# picalc.rb
# Ruby program used to calculate pi using the
# Gregory-Leibniz Series as defined at
# http://en.wikipedia.org/wiki/Pi#Calculating_.CF.80
# @author Mark Stump

numerator = 4.0
denominator = 1.0
numiterations = 100000000
numAt = 1.0
negval = 1.0
answer = 0.0

numiterations.times do
answer += (negval) * (numerator/denominator)
negval *= -1
denominator += 2

puts "The calculated value of pi is"
puts answer

And now, the test:

The calculated value of pi is

real 2m22.319s
user 2m16.693s
sys 0m0.429s
Ophanim:~/picalc Gatacoma$


Ah yes, Perl. The “Swiss Army Chainsaw” of scripting languages. I had no experience with Perl before this experience (nor with Ruby), but I found it fairly simple to implement the program. However, I did notice something while writing the code: It seems like in advanced implementations, it could get really ugly, really fast.

Even so, I found Perl, like Ruby, very no-nonsense in it’s implementation and was very efficient in it’s coding.

Perl, like Ruby, is an interpreted language, so it is not compiled before it is run.

The source code:

# Script created for calculating Pi
# Uses the "Gregory-Leibniz" Series
# Found on http://en.wikipedia.org/wiki/Pi#Calculating_.CF.80
# Author: Mark Stump

$numerator = 4;
$denominator = 1;
$negVal = 1;
$calculatedVal = 0;

# Number of iterations for loop to calculate pi
$numIterations = 100000000;

for $1 (1 .. $numIterations) {
$calculatedVal += $negVal * ($numerator/$denominator);
$negVal *= -1;
$denominator +=2;

print "The calculated value of pi with ",$numIterations;
print " cycles of the calculation loop is: \n";
print $calculatedVal, "\n";

And the results:

Ophanim:~/picalc Gatacoma$ time perl picalc.pl
The calculated value of pi with 100000000 cycles of the calculation loop is:

real 1m0.654s
user 0m56.448s
sys 0m0.199s
Ophanim:~/picalc Gatacoma$


I like C. I have more experience with C++, but I haven’t felt like coding this program in that language yet. C is a language that is used for lower-level programming as well as operating-systems programming. From my experience, it is very fast and is generally efficient at what it does. I don’t really have enough experience with C to make many more observations, but I’m very sure I’ll become very familiar with this language as my time at RIT passes.

C is a compiled language, which aids in its efficiency and quickness.

Source code:

Edit: I can’t seem to get the source code to copy right. If anyone wants to look at it, feel free to contact me. Same as the java code.

The results:
Ophanim:~/picalc Gatacoma$ time ./picalcC 100000000
The calculated value of pi after 100000000 iterations is: 3.141593

real 0m1.607s
user 0m1.561s
sys 0m0.009s
Ophanim:~/picalc Gatacoma$

Beats the pants off of the interpreted langauges

Ah Java, my old friend and nemesis. I have more experience in Java than any language, and I’m fairly comfortable with doing a good deal of implementations in it. This does not, however, mean that I’m particularly fond of it. Java is, like any other programming language, a tool. And any tool is good for its own set of jobs. You wouldn’t use a hammer to screw in a.. er… screw. I’ve heard (I haven’t tried) that Java is very good with graphic-type programs and that it also has a very good network interface. I do not have extensive experience with either, although I do like the simplicity that the Java.net package provides.

Java appears to be to have the most overhead of the languages I used. It was the only code where I had to catch an exception due to my converting of a string to an integer from the command line (I did the same thing in C, but C didn’t force me to catch an exception). Also, a good deal of my code in the program comes from my experience, and it may be unnecessarily bloated. Even so, I believe that Java requires more code than is necessary for what I am doing in this program.

Java, like C, is a compiled program. It differs from C in that it runs in a virtual machine that allows the Java program to be platform independent.

The results:

Ophanim:~/picalc Gatacoma$ time java picalc 100000000
The calculated value of pi after 100000000 iterations is:

real 0m1.717s
user 0m1.632s
sys 0m0.042s
Ophanim:~/picalc Gatacoma$

Closing Remarks

This was purely an exercise I did in my spare time. I enjoyed the time I put into this program, and felt that it gave me a wide spread of results which all proved to be interesting.

I tried to keep the code as similar in each program as possible. I did run into some snags (such as that fact that Ruby doesn’t have a “for” loop), but I felt I generally succeeded in keeping the programs very similar.

Finally, I realize that using scripting languages for something like this may be something akin to “Square Peg, Round Hole.” I didn’t do this to find the most efficient implementation of the algorithm; I did it to see how each language was to code under the same condition.

I plan to keep doing exercises like this, if I have the time. If anyone has any suggestions for an algorithm to try or something to implement, fell free to contact me at mas1447#at#rit#dot#edu.


7 Responses to “What do I do in my spare time? Well, I calculate Pi.”

  1. Gaurav Arora Says:

    please send the c++ source code on my email.

  2. naamhin Says:

    very interesting. could you please send me the source code for c and java?

  3. naamhin Says:

    could you please send me the C coding?

  4. Nemo Says:

    May I please have the C and Java codes sent to e-mail address.

  5. Will Says:

    Can you send me the C and Java please? Thank you.

  6. Ishan Says:

    Hey can u give me some info on how to calculate pi value till 1 million decimal places…i want a frequency distribution of digits
    In ruby 🙂
    I m a beginner

  7. jbrannan Says:

    I know it’s been a while, but…

    Your perl code (or any of the listed languages, with little modification) can be run much faster (because of a much faster rate of convergence) using the Leibniz series and a Wijngaarden transformation.

    # This is the basic Leibniz series for calculating PI
    sub calcPi_GL {
    my $max = shift;
    my $sum = 0;
    $sum += ((-1)**$_)/(2*$_+1) foreach (0..$max);

    # This is the transformation. It takes two numbers,
    # and calculates the partial sums of the series using
    # recursion. The base case (when the first number is
    # 0) uses the Leibniz function to calculate the sum.
    sub piFrom {
    my $from = shift;
    my $to = shift;

    if ($from == 0) {
    $sum = calcPi_GL($to);
    } else {
    $sum = (piFrom($from-1,$to) + piFrom($from-1,$to+1)) / 2;

    piFrom(15,15) returned Pi to ~14 decimal places and is as fast as calculating about 200 terms using the Leibniz series. Just something to think about!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: