Pi Day was this week, so to celebrate, we're going to explore a quick walk of the digits of Pi. John Venn, known for the Venn Diagram, was the first person to diagram a random walk of the digits of pi. He assigned an angle to each digit and essentially described a logo algorithm for drawing the walk. We've built a logo interpreter, so let's extend it and visualize pi!

## Project

I've got the logo interpreter pulled down. We need some digits of pi to start with, so let's copy those in:

`cp ~/tmp/digits_of_pi.txt ./examples`

Now we'll start a new example:

`vim examples/pi_walk.exs`

Let's read in the basic example to get started:

```
import Logo.Instance
{:ok, logo} = Logo.Instance.start
logo
|> pen_down
|> move_to({300, 300})
Logo.Window.start(logo)
```

We'll pull in the digits of pi and put them in a list:

```
pi =
File.read!("./examples/digits_of_pi.txt")
|> String.strip
|> String.graphemes
```

Then what we want to do is reduce the digits of pi into a function that will perform our manipulations on our logo instance:

```
Enum.reduce(pi, logo, fn(digit, acc) ->
PiWalk.walk(logo, digit)
end)
```

Now all that's left to do is to define this `PiWalk`

module to perform the actual
walk against the logo instance.

```
defmodule PiWalk do
# We'll import Logo.Instance just so we have access to the functions from it
import Logo.Instance
# We'll define an angle for each digit. Since we have 10 digits, we'll
# increase by 36 degrees each time.
def angle_for("0"), do: 0
def angle_for("1"), do: 36
def angle_for("2"), do: 72
def angle_for("3"), do: 108
def angle_for("4"), do: 144
def angle_for("5"), do: 180
def angle_for("6"), do: 216
def angle_for("7"), do: 252
def angle_for("8"), do: 288
def angle_for("9"), do: 324
# Each digit will walk by 20 units.
def walk_distance, do: 20
# Then our walk function will just turn by the appropriate angle and walk
# forward the appropriate distance.
def walk(logo, digit) do
logo
|> right(angle_for(digit))
|> forward(walk_distance)
end
end
```

We can run it with `mix run examples/pi_walk.exs`

. Pretty neat, I think, and a
nice way to celebrate Pi Day.

## Summary

This was a pretty quick way to visualize pi in an interesting fashion. If you want to make it more interesting, you could tweak the color based on the location of the turtle on the canvas when the line starts, or on the total distance traveled. That would get you a design somewhat similar to the gigapan link provided in the resources section. I hope you enjoyed Pi Day. See you soon!

Comments for Pi Walk With Logo