A Slice of Pi

Archimedes poised to measure a circle behind him in the distance.

Circles. Those fascinating geometric shapes have perplexed us for millennia. The Babylonians began poking at these mysterious objects 4,000 years ago and discovered that the distance around a circle was slightly greater than 3 times its width, specifically 3 1/8 or 3.125, which they recorded on a stone tablet. About the same time, Egyptians, seeking the area of a circle, estimated the ratio to be 3.1605 and recorded their estimation in the Rhind Papyrus (1650 BC).

Fast forward to ancient Greece, Antiphon and Bryson of Heraclea developed the innovative idea of inscribing a polygon inside a circle, finding its area, and doubling the sides over and over. Unfortunately, their approach meant finding the areas of hundreds of tiny triangles, which was complicated and yielded very little results. Then came Archimedes. Instead of computing area, he focused on estimating the circumference based on the sum of the perimeter edges of the polygons. Imagine iteratively doubling the sides of these polygons, slicing them into many tiny triangles, each subdividing the former and pushing closer to the circle’s edge. Using a theorem from Pythagoras, Archimedes was able to compute the length of the sides of these right triangles. As he progressed, dividing the former triangles into smaller ones, an ever more accurate estimation of the circumference emerged. He started with a hexagon, then doubled the sides four times to finish with a 96-sided polygon. Through this method, he narrowed down the value to between 3 10/71 and 3 1/7 (3.141 and 3.143).

Using right triangle geometry and Pythagorean theorem, a2 + b2 = c2, you can compute the length of the edges to approximate the circumference of the circle.

Over the centuries, mathematicians across cultures and continents refined these approximations, each contributing a piece to the puzzle of this magical number. However, it wasn’t until the 17th century when mathematicians like Ludolph van Ceulen calculated this golden number to an unprecedented 35 decimal places. Humanity’s relentless pursuit of mathematical precision didn’t stop there. Our fascination with this mysterious golden ratio continued to motivate mathematicians, engineers, and enthusiasts alike. In 2022, researchers at Google announced computing it to 100 trillion decimal digits.  We still haven’t found the end. Its digits extend infinitely, never repeating in a discernible pattern, yet holding the key to understanding the fundamental property of circles. 

Of course, this fascinating ratio is the number we call Pi, represented by the Greek letter π. As we approach Archimedes estimate of 3.14 on our calendars as March 14, Pi Day, let’s celebrate the enduring curiosity and perseverance of our human family that led to the discovery of this remarkable number. It reminds us that even the most complex mysteries can be unraveled with dedication and ingenuity.

Here is a slice of Pi you can take with you this week. This simple python script will compute Pi to 100 places using Archimedes’ approach:

https://gist.github.com/jasonacox/dfc3f1c1d4e630009c80797352d81c32

Python
from decimal import Decimal, getcontext

def pi_archimedes(n):
    """
    Calculate Pi using Archimedes method with n iterations to estimate Pi.
    This method approximates Pi by calculating the perimeter of a polygon 
    inscribed within a unit circle.

    Polygon edge lengths are computed using the Pythagorean theorem and 
    the geometry of the polygons. The number of sides of the polygon is
    also doubled in each iteration, as each side of the polygon is 
    bisected to form a new polygon with twice as many sides.

    The formula is:
        sides = 2 * 2^n
        length^2 = 2 - 2 * sqrt(1 - length^2 / 4))

    After n iterations, the function returns the approximate value of 
    Pi using the formula:
        perimeter = sides * sqrt(length^2)
    """
    polygon_edge_length_sq = Decimal(2)
    polygon_sides = 2
    # Start with a line, then a square, then a octagon, etc.
    for _ in range(n):
        polygon_edge_length_sq = 2 - 2 * (1 - polygon_edge_length_sq / 4).sqrt()
        polygon_sides = polygon_sides * 2
    return polygon_sides * polygon_edge_length_sq.sqrt()

# Set the number of decimal places to calculate
PLACES = 100

# Calculate Pi with increasing iterations until the result converges at
# the desired number of decimal places
old_result = None
for n in range(10*PLACES):
    getcontext().prec = 2 * PLACES  # Do calculations with double precision
    result = pi_archimedes(n)
    getcontext().prec = PLACES      # Print the result with single precision
    result = +result                # Rounding
    print("%3d: %s" % (n, result))
    if result == old_result:        # Did it converge?
        break
    old_result = result

References

A Tribute to Game Changers

Jerry had a new idea. The coin operated arcade game he had developed in his garage was cutting edge. Instead of using discrete logic hardware that typically drove video arcade games, Jerry decided to use a microprocessor. His microprocessor-driven arcade racing game, called Demolition Derby never made it past field testing to appear in the video arcade scene, but a year later, Gun Fight appeared as the first widely released microprocessor-based arcade video game. What Jerry had developed in his garage became a real game changer. But his biggest contribution was yet to come.

Jerry Lawson was born in New York City. His dad was a dock worker, a longshoreman, who was fascinated with science and along with his wife, always encouraged Jerry’s interest in scientific hobbies, including ham radio, chemistry and electronics. After college, Jerry moved to San Francisco and took a job in the sales division of Fairchild Semiconductor as an engineering consultant. It was there that his garage experiment became a reality. He was promoted to Chief Hardware Engineer and Director of Engineering and Marketing for Fairchild’s video game division. He also became one of the two sole black members of the Homebrew Computer Club, a group of early computer enthusiast that included well-known members, Steve Jobs and Steve Wozniak.

One of the problems with video games at the time was that they were hardcoded to just one game. Home game devices had been created but they were limited to the games you could store in hardware. Jerry knew that the home gaming market could be expanded if they were able to offer a way for consumers to change out the game in a convenient way. He set to work on a new idea. Based on the previous pioneering work he did in moving from complex discrete logic to a software microprocessor-driven design, Jerry knew there had to be a way to make that software portable. He moved the game code to ROM (read only memory) and packaged it into a highly portable cartridge that could be repeatably inserted and removed from the console without damage. This would allow users to purchase a library of games to enjoy, effectively creating a new business and revenue stream for console manufactures and game developers.

Jerry’s invention, the Channel F console (the “F” stood for Fun) included many pioneering features. It was the first home system to use a microprocessor, the first to include a detachable joystick, the first to give users a “pause” button and of course, the first to have swappable ROM cartridge-based games. Sadly, the console was not successful, but the invention changed the home gaming world forever. A year later, a gaming console came to market using Jerry’s revolutionary concepts, and took over the world, the Atari 2600. Many other game consoles followed with the explosion of games and options for the consumer.

Jerry changed the industry! Despite his two game changing products being market failures, his ideas lived on and created a new industry. He is now recognized, honored and celebrated as the “creator of the modern video game console”.

I don’t know about you, but Jerry and his story inspired me. I see brilliant minds all around us. They dream into the future and even implement pioneering work that changes the game. Sadly, many go unnoticed until they are gone. Jerry’s story reminds us that we should applaud these pioneers. They help nudge technology and our human experience forward. We should celebrate them, acknowledge them and honor them. I know some of you are pioneers too. Keep innovating, dreaming, creating, building and inspiring! We need the game changers!

Eureka! Eureka!

“Eureka!  Eureka!” –  Archimedes

The famous Greek mathematician, physicist and astronomer, Archimedes had been given the task to verify that the king’s crown was made of pure gold.  The king suspected the goldsmith had somehow cheated him, perhaps by mixing in a cheaper metal like silver.  But he had no way of proving that so he asked Archimedes to figure it out. One day Archimedes was contemplating this problem while taking a bath. He happened to notice how the water was being displaced as he stepped into the full tub, spilling out all over the floor.  He remembered that silver weighs less than gold by volume.  It suddenly dawned on him that if he were to take the same amount of pure gold by weight as the crown, and put it into water, it should displace (spill) the same amount as the crown.  Archimedes was so thrilled with this discovery that he immediately hopped out of the bath and ran to tell the king, exclaiming “Eureka!” which means, “I found it!”.   In case you are curious, when Archimedes tested the crown, he discovered that it displaced more water than gold, indicating it was less dense (not pure gold).  So, indeed the king had been cheated by the goldsmith. You can probably guess what happened to the goldsmith!

Learning is hard.  There really isn’t a way around it.  If you want to learn something, it’s going to take effort.  I often use the excuse that the human brain is optimized to save energy.  We build models and synaptic connections to do things “without conscious thinking.”  We process huge amount of sensory data every day.  We are faced with a plethora of problems we need to solve. It would be overwhelming if it wasn’t for these optimized unconscious neural pathways that allow us to sort, react and perform our tasks without much thought.  

Learning builds more capability.  At some point in our past, we learned something new and, Eureka!  That learning was forged in our brains.  It allowed us to perform our duties while we engage our higher brain functions for more important tasks like daydreaming, pondering the next season of Loki, or wondering what’s for dinner.  Ok, so maybe those aren’t more important tasks, but you get the idea.  By leveraging our learning, we expand our capacity to respond well to incoming tasks, difficult challenges, complex changes and even enjoyable exercises. 

Learning builds on learning.  I know that sounds a bit meta, but if you examine your own experience, you know that learning builds pathways to future learning. I remember the first time I learned to program a computer.  It was hard!  I was 12 years old and wanted to make my new computer display a Christmas tree for the holidays.  Somewhere in the midst of typing in some code from a Dr. Dobbs Journal article, a Eureka moment hit and I understood the procedural flow that was happening.  I had looked at more advanced programming techniques but they were out of reach for me, at least until I hit that Eureka moment.  Suddenly that complexity was unlocked.  That eventually led me down the path to discover microprocessor design, compiler construction and operating system development.

I recently purchased some dev kits, including a LIDAR kit.  This past weekend I decided to learn how to use it to image my room as a stepping stone to my larger robotics navigation project.  The funny thing about learning is that it often takes you on roads you didn’t expect to go.  LIDARs are basically spinning measuring devices that use a laser to measure distance and send back angle and distance data.  I wanted to visualize what the LIDAR was reading but the kit didn’t provide any imaging tools.  So, I decided to learn OpenGL to render the output on my Mac. That became an exercise in itself but by the end of the weekend, I had a working project (see https://github.com/jasonacox/OpenGL-LIDAR-Display).  It was challenging and frustrating at times.  But as with any good learning effort, I had a Eureka moment that unlocked excitement and plans for future learning.  I’m looking forward to the next phase!

What are you learning?  When was the last time you had a Eureka moment?  If you haven’t already, make plans this week to tackle something new to learn.   Keep learning!

A Sonic Revolution

“We knew it could become big but could have never imagined it would be a revolution.” – Lou Ottens

Magnetic tape was genius!  A ferric oxide placed on a thin plastic film allowed the world to record, store and playback audio.  It revolutionized broadcasting, radio and especially, music.  In 1960, the portability of that music was still captured in a clumsy 7-inch reel.  It wasn’t easy to play. You needed a hefty machine the size of a small suitcase.  Lou wasn’t happy with that.  

Lou loved technology.  He was ever the engineer and loved solving problems.  As a teenager during World War II, Lou made a radio for his family so they could listen to programs like Radio Oranje.  To avoid the Nazi jammers, he even constructed a primitive directional antenna.  Just as he had made those freedom broadcasts accessible to his family, he now turned his attention to democratizing music.

The 7-inch music reel was too bulky and awkward for the general population.  He wanted music to be portable and accessible.  He thought a lot about what it should be like.  Trying to envision something that didn’t yet exist, he began shaping it into a small wooden block.  It needed to be small enough to easily fit in your hand and more importantly, fit in your pocket.  His “compact cassette” tape came to life in 1963 and quickly became a must-have sensation across the world.  It unleashed a multi-billion dollar industry but also taught us how to use our own voice.  The cassette became an audio canvas for the masses to self-create their own albums or compile their own mixtapes to share with others.  For those of you who don’t have as many candles on your cake as I do, mixtapes were basically the playlists of the 1980s.

The cassette tape was a raging success, but Lou wasn’t happy with it.  He complained about the noise and distortion that would eventually plague the aging tapes. In his mission for higher fidelity, he worked with his company, Philips and Sony to co-develop the digital optical storage system, the compact disk (CD).  As he had done with the cassette tape, Lou championed a portable disk size that could be easily held and used.

Lou Ottens passed away earlier this month, at the age of 94.  He sparked a worldwide sonic revolution, but humbly dismissed his role as nothing special, instead crediting other engineers and designers for bringing his ideas to life.  Lou reminds us that making science and technology accessible is just as important as the discovery itself.  

Do we make our complex technical inventions and solutions accessible?  When technology is done well, the technology itself fades to the background and becomes “indistinguishable from magic”.  That is to say, it provides a human experience and value and doesn’t get in the way.  My challenge to us this week is to examine the solutions we deliver and ask ourselves, can we make them more accessible and magical?  

As Lou taught us, the genius of a great idea is not just in the science, it is making that technology portable and accessible.

A Pocket of Curiosity

“I’m just very curious—got to find out what makes things tick… all our people have this curiosity; it keeps us moving forward, exploring, experimenting, opening new doors.” – Walt Disney

Percy Spencer only had a fifth-grade education. His father passed away when he was a toddler and he left school to get a job to support his family when he was only 12. His formal education may have been cut short but that didn’t stop his learning.  He began to experiment with electricity and learning at night, after work.  He became intrigued with wireless radio when he read how it was used to direct the ship Carpathia to rescue the Titanic passengers. He joined the Navy and managed to get ahold of textbooks to teach himself mathematics and science. After his service, he was hired at Raytheon, a newly formed company designing and manufacturing vacuum tubes.  Percy was particularly interested in producing radiation, specifically the use of magnetrons to generate signals used in radar.  That was something the US Government was keen to get for the war efforts.

One day in 1945, Percy showed up at work with a chocolate candy bar hidden in his pocket. While standing in front of the magnetron he was working on, he noticed the candy bar was melting.  He was fascinated by this behavior so he sent out for some unpopped popcorn and put it in front of the magnetron.  When it popped, he knew this small wave radar radiation could be used for cooking. He put the magnetron in a metal box and thus was born the first microwave oven.

Curiosity leads to discovery.  A disadvantage can often lead to a profound benefit.  What makes the difference?  In the case of Percy Spencer, his self-guided education taught him to ask why, to experiment and learn.  An unexpected occurrence, which by all rights could be viewed as an embarrassing disaster by many of us (melted chocolate pocket anyone?) turned into a critical discovery that has brought about an amazing benefit to humanity.  His creative idea was born out of curiosity, observation and action.

This year has been challenging for all of us. The new ways of working and the difficulties before us can be perplexing and discouraging at times.  But don’t give up.  Turn that melted chocolate bar into a discovery.  Ask, what can we learn from this crisis?  What experiment can we conduct to lead us on to discovery?   Are you limiting yourself or your thinking by the echo chamber we can easily find ourselves in?   Don’t.  Try something new this week.  Observe, ask why and then seek to answer it.  I suspect we are all sitting on a goldmine of new discoveries that we have yet to entertain.  Tap your opportunities and explore the unknown to see where it leads.

The next time you heat something up in the microwave remember how a melted candy bar and an inquisitive person handed us that useful invention.

An Ocean of Science

“You must never confuse faith that you will prevail in the end—which you can never afford to lose—with the discipline to confront the most brutal facts of your current reality, whatever they might be.” – Admiral Jim Stockdale

It was hot in our valley this past week!  I built a simple outdoor weather station that displays current temperature, pressure and humidity.  This is the first time I saw it go above 114°F (45°C).  I was never so glad that I had planned time off and we had arranged for home healthcare to stay with my mother-in-law so that my wife, daughters and I could get away for a day.  Our big vacation was a trip down the 126 freeway to Ventura. 

Sometimes the simple things are best.  We parked at the beach, rolled down the windows and enjoyed the cool breeze.  We ate lunch in our van and watched the surf perform its dance across the shore.  It was like each wave was an ocean exhale reminding us that time keeps moving forward.  Its cool breath swept up the beach and gently across our faces.  It was serene and relaxing. 

As you can imagine, we were not the only ones to have this brilliant idea.  The streets and beaches were full of cars and people.  Sadly, most were not wearing masks or even attempting to social distance as they wandered about between the parking lots and beaches.  It struck me how difficult it has been for us to maintain vigilance in this area as we enter our 6th month of this pandemic.  I understand the frustration and know the desire to get back to normal, without face masks, distancing or shields.  There is a temptation to dismiss the science, minimize the seriousness or even justify rebellion against these safety measures.  Some of us figure that if we ignore it, it will just go away.  Unfortunately, that can only prolong and increase the impact.

We must never lose hope.  As the ocean reminds us that time marches on, so must we.  But that faithful determination must be coupled with discipline to confront reality.  As engineers, science is the illumination and tool of our profession.  We practice the scientific method to systematically experiment, learn and devise solutions.  Uncertainty, mystery and fear are chasms that we can bridge with methodical, step by step discovery and progress.  We can tunnel through difficult realities with cunning application of knowledge and persistence. The same can apply to this coronavirus pandemic and to the challenges in our businesses.  We can use our skills and expertise to help chart a solution forward.

Are we or others assuming or inventing a reality inconsistent with our scientific training?  Are there problems in front of us that could use a methodical approach to fully uncover and fix?  Do we set the example for others of being helpful, but logical, optimistic but scientific in our approach?  While 2020 has been an extremely challenging year, it is also a reminder that we have come a long way as a human family.  Behind us is an ocean of knowledge, discovery and tools that can amplify our ability to help those before us.  This week, I challenge you to tap that reservoir and heroically apply your talents to the problems at hand.  Strengthen your mind with hope and logic and let the winds of knowledge propel us forward.  And please, like other super heroes, wear a mask.  Stay scientific (and safe) out there!

Home Automation – SentryPi

Who left the garage door open?

We have a full house with a lot of activity and visitors.  There have been several times when the garage door is left open for extended periods of time.  While our Christmas decorations and paint supplies may not be a treasure most would be thieves would desire, it is still not the most comforting thing to think about leaving the garage open for all passerby to see.  I often thought it would be great to have a way to notify whoever is in the house that the garage is open.

Phase 1 – LED Indicator

I decided that my first step would be to design a way to detect “door open” by providing a simple indicator light.  I explored a few optical ways to do this (light beam, camera, reflectors) but quickly pivoted my approach when I found some unused microswitches.

I found a good place to detect “closed” on the main track.  I thought about piggybacking on the garage opener sensors but dismissed that as I didn’t want to risk an undesirable interaction with the opener and more importantly, I wanted to have the detection work even if power to the opener was interrupted.

This required that I build a bracket to mount the switch to and a ramp plate to compress the switch when the door was in the down position.

I used an aluminum sheet, cut with sheet metal snips,  bent and drilled holes to mount the microswitch and eventually attach it to the garage door track.  It took a few tries to get the right fit and right placement of the micro switch.

My first attempt destroyed the microswitch after a few uses.  The garage door track sled has a straight edge that collides with the microswitch roller. It created too much force on the small roller and eventually popped it loose.  To help with that, I added an aluminum ramp to the sled so that the microswitch roller would gently rise as the sled entered the “closed” position.

I decided to make the “door open” state be the closed circuit condition so that phase 1 of the project could start as a simple LED circuit indicator.

I attached the switch and drilled some pilot holes and mounted the bracket to the garage door track right above the sled when the door is in the closed position.

I added a 9V battery, a 470 ohm resister and a red LED to the circuit.  To complete this phase, I ran the wire from the garage to our entry hall and mounted an LED and housing above the HVAC controls.  Now we can all see the brilliant red LED glowing when the garage door is open.  That covers some of our use cases but I also want a more proactive notification.  Now on to phase 2…

Phase 2 – Raspberry Pi – Home Automation Sentry

Now that I have a working “door closed” sensor and indicator, I am ready to add the proactive home automation component, specifically the Raspberry Pi (RPI).  It just so happens that I have a spare RPI Model 3 that needed a project, and I wanted to experiment with AWS IoT services.

I used the RPI to detect the state of the switch. To do that, I will need to wire the circuit into the RPI’sGPIO headers.  I decided to use GPIO Pin 23 and the adjacent ground (GND) pin.

Here is the code that is used to detect the closed circuit (indicating an open door):

#!/usr/bin/python

##  
## Garage Door Sentry - RPI script to monitor door
##  

## load libraries
import RPi.GPIO as io 
import time 

print "Garage Door Sentry\n\n"

## set GPIO mode to BCM - allows us to use GPIO number instead of pin number
io.setmode(io.BCM)

## set GPIO pin to use

door_pin = 23
print "Sentry Activated - Watching: GPIO 23"

## use the built-in "pull-up" resistor
io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP)  # activate input

## States for door: 0=closed, 1=open, 2=init
door=2
## infinite loop
while True:
    ## if switch is open
    if (io.input(door_pin)==True and door!=0):
        door=0 
        print "Door closed"
        # do some action
    ## if switch is closed 
    if (io.input(door_pin)==False and door!=1):
        door=1 
        print "Door open"
        # do some action
    time.sleep(1) # 1 second wait

The next step was to connect to AWS IoT to record this sensor data and send alert messages to my phone.

The following will help you set up your Raspbery Pi as a platform to install the SentryPi scripts.

Required:

  • Raspberry Pi – B+, 2 or 3
  • Wifi Dongle or Network Cable configured
  • SD card (Recommend: 16GB or larger)
  • AWS Account (IoT, DynamoDB)

Read the details on this GitHub Project: https://github.com/jasonacox/SentryPi

The project describes how I added these additional features:

  • Sentry Alert – Send a text message to contacts when an alert condition is reached.
  • Dashboard – Provide an automation dashboard for realtime status.
  • Other Sensor Data:
    • Temperature Sensors
    • Barometric Pressure Sensor
    • Humidity Sensor
    • Motion Sensor

To set up a web based dashboard, I decide to use static HTML, CSS and JS (jQuery, Chart.js and the AWS JavaScript SDK) so it can be hosted on a simple S3 bucket, a web server, or the RPi itself.  See here for the code. 
SentryPi Dashboard
SentryPi Dashboard - Garage Door Graph

To Engineer is Human

To Engineer is Human: The Role of Failure in Successful Design by Henry Petroski

This is a great book to remind us of the purpose of engineering and the dangers we face when designing technical bridges (and physical ones) across the unknown.

Petroski wrote this in the early 80’s and the examples and illustrations are sometimes dated but still practical. I found the section on computers, “From slide rule to computer” to be particularly interesting.  His case still hold true for the faster/newer techno-driven culture of the 21st century.

We have come to be a society that is so quick to change that we have lost the benefits of one of mankind’s greatest tools–experience.   – Henry Petroski

Engineering is very dependant upon feedback for improvement.  The goal of providing a design solution for the lowest cost will mean that materials, processes and other costly items will be minimized to achieve the most economical/efficient solution.  Unfortunately, there are things that we do not know about (the trite, “we don’t know about what we don’t know” phrase comes to mind) that can be or become significant issues in the design.  The Tacoma Narrows Bridge is a great example of this.

Engineering attempts to introduce “safety factors” into the design model to cover for the unknowns but this can often be inadequate, as was the case of the walkway collapse at the Kansas City Hyatt Regency Hotel.

Failures, while unfortunate and often deadly, should also be opportunities for improvement.  Petroski argues that it is important that details of failures be broadcast to provide corrective feedback to all engineers so that future designs will build on these learnings.