For the love of Pi


Summary: In honor of Pi Day today, we have a guest blog post written by PowerShell MVP, Doug Finke.

Image of apple pie with Pi character

Photo courtesy of Ed Wilson

It's that time of year again when lovers of math, geometry, Albert Einstein, food, and Windows PowerShell can stop and reflect on that transcendental irrational number, Pi. It's the ratio of a circle's circumference to its diameter or "Hey, can I get a slice of that Pi?".

Approximate Pi

The best we can do is approximate Pi, 22/7 (go ahead, type that into a PowerShell console). The first recorded algorithm for rigorously calculating the value of π was a geometrical approach using polygons, which was devised around 250 BC by the Greek mathematician, Archimedes.

Here we calculate π to 8 decimal places in only 13 iterations.

# http://www.craig-wood.com/nick/articles/pi-archimedes

function pi_archimedes($n) {
# Calculate n iterations of Archimedes PI recurrence relation

$polygon_edge_length_squared = 2.0
$polygon_sides = 4

if($n -gt 0) {
0..($n-1) | % {
$polygon_edge_length_squared = 2 - 2 * [math]::sqrt(1 - $polygon_edge_length_squared / 4)
$polygon_sides *= 2
}
}

$polygon_sides * [math]::sqrt($polygon_edge_length_squared) / 2
}

0..15 |% {
$result=pi_archimedes $_
[pscustomobject]@{
iteration = $_
sides     = [math]::pow(2, ($_+2))
result    = $result
error     = [convert]::ToDecimal(($result-[math]::PI).ToString("N9"))
}
}

After iteration 13, the estimate of π starts getting worse. You can improve this by improving the precision of the calculation, which is left as an exercise to the reader.

iteration       sides      result                            error
---------         -----        ------                             -----
0                        4       2.82842712474619    -0.313165529
1                         8       3.06146745892072   -0.080125195
2                      16        3.12144515225805    -0.020147501
3                      32       3.13654849054594  -0.005044163
4                      64       3.14033115695474    -0.001261497
5                    128       3.14127725093276   -0.000315403
6                    256       3.14151380114415     -0.000078852
7                    512       3.14157294036788   -0.000019713
8                 1024       3.14158772527996    -0.000004928
9                 2048       3.14159142150464    -0.000001232
10               4096       3.14159234561108    -0.000000308
11                8192       3.141592576545         -0.000000077
12             16384       3.14159263346325    -0.000000020
13             32768       3.14159265480759    -0.000000001
14             65536       3.14159264532122    -0.000000008
15            131072       3.14159260737572    -0.000000046

Food lovers

Let's turn our attention to getting some Pi recipes, like apple and cherry.

Image of apple and cherry pies

Photo courtesy of Ed Wilson

Here's a function, Get-Pi, that uses the Microsoft Bing API.

Note: You need a Bing API key to make it work.

function Get-Pi{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
$q
)

Begin {
Add-Type -Assembly System.Web

$Key=$env:BingPicKey
if(!$env:BingPicKey) {
Throw '$env:BingPicKey needs to be set'
}

$Base64KeyBytes = [Text.Encoding]::ASCII.GetBytes("ignored:$Key")
$Base64Key = [Convert]::ToBase64String($Base64KeyBytes)
}

Process {
$query=[Web.HttpUtility]::UrlEncode($q + ' pi')

$url = "https://api.datamarket.azure.com/Bing/Search/Web?`$format=json&Query='$query'"

$r=Invoke-RestMethod $url -Headers @{ 'Authorization' = "Basic $Base64Key" }

$r.d.results| % {
[PSCustomObject][Ordered]@{
PiType = $q
Description=$_.description
Url = $_.Url
}
}
}
}

In action

Let's get the Pi recipes for these classics.

echo cherry chicken apple | Get-Pi

Here is a modified version of the output.

PiType  Description
------  -----------
cherry  Bake an all-American Cherry Pie recipe from Food Network using fresh
cherry  Directions. Mix ingredients for filling. Place in pastry-lined pie p
cherry  Looking for a fruit dessert? Then check out this delicious pie with
cherry  Looking for cherry pie recipes? Allrecipes has more than 60 trusted
cherry  Summary. UPDATE 13 April 2014 ... It rips through the Cherry Pi's bo
chicken Get this all-star, easy-to-follow Chicken Pie recipe from Trisha Yea
chicken Use a prepared double-crust pie pastry to help achieve this easy, be
chicken Make your leftover chicken into the ultimate comfort food with a few
chicken Get this all-star, easy-to-follow Chicken Pot Pie recipe from Ree Dr
chicken I found this on another site. It is a fun and different way to serve
apple   A classic apple pie takes a shortcut with easy Pillsbury« unroll-fil
apple   I remember coming home sullen one day because we'd lost a softball g
apple   Winners of the Washington Apple Pi Photo Contest 2015 were announced
apple   This is the apple pie I’ve been making for years and if using Pillsbu
apple   For a touch of homegrown comfort, bake Bobby Flay's classic Apple Pi

Happy Pi Day

From math to code to search APIs, that's a quick tour for today. I encourage you to tour the Internet and read up on this magical number, and as a bonus, here is Get-BingPics on GitHub. It uses the same approach that we’ve seen, but the output is not text. Instead, the output is an HTML document with each image URL embedded in it. Click the following image to open a new window and see Get-BingPics in action.

Click the image to see animation of Get-BingPics results.

Thank you, Doug, for an excellent Pi Day blog post.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guy Forum. Also check out my Microsoft Operations Management Suite Blog. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Comments (1)

  1. Slav Pidgorny says:

    I have written Pi approximation in a tweet (the more n is the better approximation):

    $n=5000; $x=0; foreach ($a in 0..$n) { foreach ($b in 0..$n) { $x += [int]($a*$a+$b*$b -le $n*$n) } }; $x*4/($n+1)/($n+1)

    Happy Pi Day!

Skip to main content