Computer Science

Happy Pi Day!

It's Pi Day! The ratio of a circle's circumference to its diameter—an irrational number, with its infinite number of digits—seems to hold a special place in the hearts of many.

0. Video Warm-Ups

1. Calculate Pi (recursively or with a loop)

Write a program that finds and outputs a calculated value of pi using recursion and the following series:

2)/6 = 1 + 1/22 + 1/32 + ... + 1/n2

The value n is the number of iterations of the recursion. Your main program will ask for a value n, and then call your recursive function to calculate the sum of the series. With that sum, the main program can then calculate the value of pi.

Finally, compare that calculated value with the value of pi available in the math library (Math.PI for Java, math.pi for Python). What is the percent difference between your calculated value and the actual value in the library? How many iterations (n) does it take your program to get to within 0.1% of the actual value of pi?

(Python solution)

2. Read the digits of pi into a program

To be able to study the digits of pi, we need to be able to read them into a program. This text file contains the first million decimal places of pi.

Right-click or control-click on the link to download that file onto your computer. Then open that file and read its digits into a program using one of the utility functions given here.

Show/hide Java code

Show/hide Python code

3. Count the digits of pi

Are the digits 0-9 evenly represented in those digits? Are there more 1s than 2s, or more 7s then 6s?

Write a program to import that text file and count the frequency of each digit.

Note for Java: You can convert a String-based integer—7, for example—to an Integer using the Integer.parseInt() method:

String stringNum = "12345"; int num = Integer.parseInt(stringNum);

4. Find your birthdate in pi

There are lot of numbers in an infinite sequence. Like... infinitely many.

Take the two-digit forms of your birth month and date to make a string of values—mine is Feb 8, or 0208—then determine where in the value of pi that string occurs.

The birthdate that appears earliest in the sequence wins!

5. Calculate Pi using the Chudnovsky algorithm

You'll need to do some research on how to do this... or you can just read about the Chudnovsky Brothers in this New Yorker article and try running one of the programs shown here.

These are "generators" that don't produce a single value at the end of solving the problem. Instead they iterate through the problem, producing a single digit at a time and display it on the screen as it goes.

Show/hide Java code

Show/hide Pi code