Wednesday, 1 January 2014

The Decline in US Coin Quality (with comparison photographs)

This is a post that only obsessive-compulsive folk like myself could care about, so bear with me. If you simply don't care about this kind of stuff (like normal people), escape to Walmart.

I have been in the US for over 2 years, and in that time I have noticed that coins minted before the mid 90's are of substantially higher quality than those minted subsequently. The old coins appear to be more '3 dimensional', and details are much finer. The difference is such that if you gave a person in the 1970's a recent coin but with a date from the 70's, I suspect it would be outed as counterfeit.

Conveniently, I have a decent camera with nice prime lens and manual focus, and can show a couple of examples.

First, let's compare a 1961 penny to a 2013 penny (by the way, I dislike pennies and think their continued production is exemplary of much that is wrong with the US government, but that's another issue).

The 1961 penny pictured below was received as change. It has been in circulation some 52 years and has bits of black crud stuck to it. It's an alloy of 95% copper, 5% tin and zinc. Observe the depth of the writing, and the very clear depth of the Lincoln bust.


Now let's look at a 2013 penny (below). It's a 99.2% zinc + 0.8% copper alloy blank, plated with 100% copper, resulting in a final composition of 97.5% zinc + 2.5% copper.


Comparing the two, I might think "Did I mess this photo up?" Apparently not, as you can see the very very tiny shadows cast by Lincoln's almost completely insubstantial bust, and that the bottom half of the coin is clearly in focus.

OK, so we all know that pennies are worthless, and that modern ones are basically copper plated chum. Perhaps the mint is cheaping-out on them, knowing that most of them are immediately thrown away.

How about Kennedy half-dollars? Below is an image of a 1971 Kennedy half-dollar. Note the pleasing depth of the US Great Seal.


To compare, below is a 2000 Kennedy half-dollar.


Yuck... What... Is... That? Yes, I know the 2000 coin is more worn because the milling is worn down, but the strike never had any depth to begin with. I also have a 1983 coin that resembles the 1971 coin.

It's not just these coins either. Quarters, nickels, and dimes also consistently show the same features. I don't have any to hand, but this effect can be very frequently seen, especially in quarters.

So why the apparent decrease in the quality of US coins? If anyone who knows how the US mint operates can comment, it would be nice to know what actually happened. Is this a cost cutting measure? Was it a design fad?

P.S. If anyone wants to know why I care about these things, it's because my parents gave me one of these:


It's not really worth anything beyond its silver bullion value, but it's a beautifully designed and made coin.

Friday, 27 December 2013

An Interactive Lambda Calculus Interpreter

Here's an interactive Lambda Calculus interpreter that I wrote back in 1997 while at Adelaide University.

It was written as a teaching tool, and allows you to reduce lambda expressions one step at a time. It can automatically choose a reduction and explain it to you, or you can manually choose the reduction to apply and the subexpression to which to apply it (by selecting with the mouse).

It's written in the latest and greatest technology for the time: a Java 1.1 application. I just gave it a shot on OpenJDK 1.7, and it (mostly) works, although it does crash occasionally. The write-up is available in PDF form at LambdaThesis.pdf. It's overlong, but provides a reasonable overview of Lambda Calculus for anyone who is interested.



Running the Interpreter


In order to run it, download LambdaTeacher.zip and unzip it (this stuff is so old that compressed JAR files weren't well supported at the time). In order to run it, install Java and execute:

java -cp LambdaTeacher.jar LambdaTeacher

(Note that the switch is -cp, not -jar ; JAR manifests didn't exist at the time). After executing it, you can use the file menu to open defines.jar to load all the bindings.

How It Works


(Note: this section is copied verbatim from a 13 year old web-page, so you can chuckle at historical details)
This interpreter uses string (as opposed to graph) reduction, and as such is very slow. On my Pentium 233, fibonacci two takes about 20 seconds to evaluate (2013 note: it's instantaneous on my 6 core Xeon with 32GB RAM ☺). It does this so the user can reduce one step at a time, and get a feel for different reduction orders.

Features:

  • Name capture detection. When a name clash is detected, it will prompt the user to type in a new name.
  • Any reduction order can be attempted. It has buttons for normal and applicative order. Other sub-expressions for reduction can be selected using a sub-expression selection dialog, where the expression to be reduced is clicked on.
  • All reductions are explained in explanation dialog boxes as they are performed.
  • Names can be bound to Lambda expressions, using let <name> = <expression>. Names aren't removed during a reduction unless the expression they refer to is modified in any way. Users can select names for removal at any time.
  • Files with definitions (name - expression bindings using the let syntax) can be read in.
  • Error messages for invalid expressions - it attempts to tell you (kind of) where the expression went wrong. If you are reading in a file, it tells you what line the problem occured on.

Non Features:

  • Single threaded. This means that while interpreting, you can't interact with the current application. If you give the interpreter a large or non-terminating expression, you'll have to kill it (Control C on the Java console should do the trick). I know this isn't user friendly, but if you're learning lambda calculus, you should be able to kill a looping process. 

Syntax

The syntax is:
<Prog> ::= <Expr> | let <Variable> = <Expr>

<Expr> ::= <Variable>
         | <Number>
         | \ <Variable> . <Expr>
         | ( <Expr> )
         | <Expr1> <Expr2>
         | +
         | -
         | *
         | /

<Variable> ::= Any string of letters.

<Number> ::= Any integer.

Source Code Availability

It's available here. The GNU Public License V2 applies. See http://www.gnu.org/ for the GPL V2.

My solution to the Go Tutorial Web Crawler exercise

I've been having a fun time learning Go. The final exercise (http://tour.golang.org/#73 at time of writing) asks you to modify a web crawler to crawl pages in parallel without fetching the same page twice.

One general rule of thumb with parallel programming is never write your own synchronisation code; it's difficult, error prone, and difficult to validate. This is true for monitor based synchronisation, and as neat as Go's channels and goroutines are1, they're still relatively low-level so I believe it's generally true for Go as well. Instead of writing your own synchronisation code, use well written libraries that provide a suitable abstraction.

There are two concurrency problems with the WebCrawler exercise. The first is the problem of making the main function wait until all spawned goroutines complete. The second is the problem of storing and accessing visited URLs in a safe manner.

For the first problem, the Go library provides a WaitGroup type in the sync package. For those who are familiar with Doug Lea's excellent java.util.concurrent package, WaitGroup is similar to the java.util.concurrent.Phaser class.

The WaitGroup type simply holds a counter. Clients can increment the counter (using Add(delta int)) or decrement the counter (using Done()). Clients can also call WaitGroup.Wait(), which blocks until the counter reaches zero.

We want to have the main routine wait for an unknown number of goroutines, so WaitGroup is perfect for our needs. Before spawning a goroutine, we simply increment the counter, and in the goroutine itself, we use Go's defer feature to ensure that the counter is decremented before the goroutine completes.

For the second problem, we need to have multiple goroutines store visited URLs, and also query all visited URLs in a safe manner. A 'test-and-set' type operation is ideal for this, so I created a Visited type with a TestAndSetVisited(url string) function which uses a sync.Mutex to protect reads and writes to a map. I considered a sync.RWMutex, but when using test-and-set semantics, a mutex is simpler. I suspect that a RWMutex may be more efficient if the URL graph was dense, but it doesn't seem worth the hassle.

Below is the tutorial code, with my modifications highlighted in green.

package main

import (
    "fmt"
    "sync"
)

type Fetcher interface {
    // Fetch returns the body of URL and
    // a slice of URLs found on that page.
    Fetch(url string) (body string, urls []string, err error)
}

type Visited struct {
    url_map map[string]bool
    mutex sync.Mutex
}

func (self *Visited) TestAndSetVisited(url string) bool {
    defer func() {
        self.url_map[url] = true
        self.mutex.Unlock()
    }()
    
    self.mutex.Lock()
    return self.url_map[url]
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, 
           visited *Visited, wg *sync.WaitGroup) {
    defer wg.Done()
    if depth <= 0 || visited.TestAndSetVisited(url) {
        return
    }
    body, urls, err := fetcher.Fetch(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("found: %s %q\n", url, body)
    for _, u := range urls {
        wg.Add(1)
        go Crawl(u, depth-1, fetcher, visited, wg)
    }
    return
}

func main() {
    var visited = Visited{ url_map: make(map[string]bool) }
    var wg sync.WaitGroup
    wg.Add(1)
    go Crawl("http://golang.org/", 4, fetcher, &visited, &wg)
    wg.Wait()
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult

type fakeResult struct {
    body string
    urls []string
}

func (f fakeFetcher) Fetch(url string) (string, []string,
                                        error) {
    if res, ok := f[url]; ok {
        return res.body, res.urls, nil
    }
    return "", nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
    "http://golang.org/": &fakeResult{
        "The Go Programming Language",
        []string{
            "http://golang.org/pkg/",
            "http://golang.org/cmd/",
        },
    },
    "http://golang.org/pkg/": &fakeResult{
        "Packages",
        []string{
            "http://golang.org/",
            "http://golang.org/cmd/",
            "http://golang.org/pkg/fmt/",
            "http://golang.org/pkg/os/",
        },
    },
    "http://golang.org/pkg/fmt/": &fakeResult{
        "Package fmt",
        []string{
            "http://golang.org/",
            "http://golang.org/pkg/",
        },
    },
    "http://golang.org/pkg/os/": &fakeResult{
        "Package os",
        []string{
            "http://golang.org/",
            "http://golang.org/pkg/",
        },
    },
}

Update: I have since discovered that fmt.Printf is not thread safe, and can interleave output. Concurrency is hard.

Also, Sonia at the Sonia Codes blog has a nice writeup of a very go-like solution to this exercise. It's 'go-like' in that it explicitly shares memory by communicating. See http://soniacodes.wordpress.com/2011/10/09/a-tour-of-go-69-exercise-web-crawler/ .



1. For an introduction to where the ideas behind Go's channels and goroutines came from, have a look at C. A. R. Hoare's Communicating Sequential Processes.

Wednesday, 25 December 2013

Fixing the shutter button on a Bigshot DIY digital camera

I recently ordered a Bigshot DIY Digital Camera kit for my 6 year old daughter's Christmas present. It's an fun little kit to assemble on Christmas day... but there was one drawback. After assembly, the shutter button didn't work; it was locked hard and wouldn't depress. This blog entry will show you how to fix that problem if it happens to you.

Warning: I don't recommend following these instructions you have assembled the camera and it works. Only do this if you have assembled the camera and the shutter button is stuck.

The Bigshot DIY Digital Camera

First, disassemble the camera by following the instructions in reverse, to the step where the shutter button is installed, shown below:


Check that you have the same issue as me by placing the PCB module into the camera. The image below shows the PCB module half-inserted. Note that the top of the white button (the internal shutter button) protruding from the top of the PCB module is higher than the bottom of the external shutter button.


Below is the PCB module fully inserted. Note that the external shutter button is making direct contact with both the camera casing (on top) and the internal shutter button (below). There's no play or extra space. Also note that the PCB module is sitting slightly lower than the screw holes. When the screws are done up, this raises the whole PCB module, causing the external shutter button to press on the internal shutter button.


I addressed this problem by taking out the shutter button, and filing about 1mm from the thick post on the button's underside.


After filing down the post, and placing the button and PCB module back into the camera, you can clearly see that there is now a small amount of space between the bottom of the external shutter button and the top of the internal shutter button.


After this, reassemble the camera according to the instructions, and you'll have a nice working shutter button. Happy snapping!