Jul 22, 2011

Analog Planimeter

I recently got one of these for my birthday:



http://www.math.ucsd.edu/~jeggers/Planimeter/KE_4242_1930/KE_4242_1930_gallery.html

It´s called a planimeter - a simple device which is used to calculate the area of an arbitrary blob. What is incredible is how simple the device is. At it's most basic, it is nothing more than two joined sticks and small wheel. It works because of Green's theorem, which is basically just the fundamental theorem of calculus (see post below). The fundamental theorem of calculus is everywhere. Mathematical!

The one I have is exactly like the one in the gallery above. It´s a 1930´s German manufactured planimeter. How did I come across this? About half a year ago, I was wandering in the beautiful stacks of the Math library at the University of Illinois. It might be one of the more interesting libraries around. The library is modeled on the throne room at Neushwarstein Castle of King Ludwig II of Bavaria, has dangerous translucent glass floors, and pictures of famous mathematicians whose gaze is at times very unnerving. The book collection isn't bad either. Although it is though a very small library by the university´s standards, they have a pile of books every month that they give away.

These days, the books are usually on some obscure branch of analysis and almost always in Cyrillic. I happened to find a book on the subject of Graphical and Mechanical Computation however.  This book was of practical use at the time of its publication, but the direction of our progress has made the techniques nothing more than curiosities. It's such a shame that progress has caused us to abandon such a beautiful technology. Fortunately, Google has preserved the book at the link above. I learned about the planimeter in some of the later chapters.

Maybe there is new interest in the subject. John D Cook recently reviewed this book on Nomology, a form of graphical numerical computation. I guess I have now another book to add to my shelf now...

Jul 13, 2011

Incarnations of the Fundamental Theorem of Calculus.

I'm not sure most people know how very often the fundamental theorem of calculus comes up. I'm  even more surprised how many people are hard pressed to be able to describe it, even if they work in a technical field were calculus is used.

The fundamental theorem of calculus basically says that deriving the rate of change of something and finding integrating the area are like ying/yang hot/cold addition/subtraction. They're complementary and undo each other.

Anyway, I'm writing this because I think I've stumbled across a kinda unintuitive result of it that shows how widespread this duality between area and rate is. I was looking at program written in Mathematica and came across the following snippet:

Mean@Differences@list

This code takes the mean of the differences of a list of numbers called list. The differences are simply the differences in the adjacent numbers: First minus Second, Second minus Third, and so on. The mean is just the average of them. The code here is inefficient. A small amount of algebra shows that there is a quicker way to compute this value than to take all of the differences and then take their means.

Let's say that our list of numbers is (a,b,c,d,e,f). Then our list of differences is (a-b,b-c,c-d,d-e,e-f). To average them, we add them all up and divide by the length of the list which is 6:

(a-b+b-c+c-d+d-e+e-f)/6

which is equal to (a-f)/6

It's not too hard to see. This result however is essentially just the fundamental theorem of calculus. This fact is not as clear - after all, there are no derivatives and integrals really used. They are discrete versions however and they are hidden in the actual problem.

First, the Differences function is a kind of discrete derivative. It is changing our list of numbers into a list of the rate of changes in the numbers. Rate of change is essentially just a derivative.

The second thing is that taking the mean of a set of numbers is kinda like integrating. In fact, most people will remember that you can take the average value of a continuous function by integrating it and dividing by the range over which you are averaging.

Putting these two together shows that they undo each other. The integral from a to z of a derivative is just the original function evaluated at a minus it evaluated at z. We divide by the length of the z-a to get the average.

Actually the correspondence between the difference operator and differentiation is kinda fun in general:

http://en.wikipedia.org/wiki/Difference_operator

Jul 4, 2011

Literature Reading Plan

First, the word "Plan" really shouldn't be here. In fact, I've chosen the title simply so I could I can write about  how my grand book reading plan is actually an un-plan. I don't want to give the impression that I've created a regime and book reading list based on the great authors. Instead, the plan is an emergent behavior - I read books I've bought by wandering around aimlessly at bookstores without any kind of timetable. I read books which are around me compulsively. This plan is a pattern which has emerged without intention in my life. 

The books aren't all things I have fun reading. In most cases, I would really prefer to be reading about math. There are a number of books on I've acquired by way of recommendation or I've prescribed to myself because I feel like they will be good for me.

I would have never been able to do this in college. Being compelled to read and lie about your views on one novel kills all of the energy needed to really read at least two or three of them. I'm amazed The

Here's a short list of the some of the types I've been reading over the past year:

Kurt Vonnegut
  • TimeQuake
  • Sirens of Titan
Like half of everything David Sedaris has written. "The Kid" by Dan Savage. 

Haruki Murakami
  • Reread Underground
  • Blind Willow, Sleeping Women
  • Wind-up bird Chronicle
The Catcher in the Rye

and a bunch of others I've forgotten or didn't feel were worth any comment. Overall, this list is a bit more impressive than I would have thought it would be a year ago. 

I think Murakami and Vonnegut are a specific kind of reading for me. Reading abusrdist literature makes you more creative. It also probably makes you more likely to go insane, but the two are closely linked. 

The other identifiable trend in my reading is clearly gay literature. Savage's work is more centrally about being gay than Sedaris's comedy. Both however are fairly important to me for being gay works.  I feel like I could be easily criticized for being a gay guy reading gay literature for sake of being gay. 

gay gay gay gay gay gay gay 

However it is important to me to see a reflection of my life in literature. Growing up, I never saw people living out gay lives.  I know a number of people who would say that I shouldn't need media like TV, radio, and books to tell me how to live, but those people always had a reflection of their lives available to them wherever they wanted it. Maybe Asian Americans feel the same way to a degree reading Amy Tan. I feel like the need to be represented in literature is kind of universal. People who don't see their own troubles reflected in books likely are not reading. 

Jun 16, 2011

Some of my best reading recently

Cicero on the Cataline conspiracy:

http://www.bartleby.com/268/2/11.html

Julius Caesar on the Catiline conspiracy:

http://www.bartleby.com/268/2/19.html

May 23, 2011

Theo Jansen's Beasts

Dutch artist Theo Jansen has been selling miniature 3D printed reproductions of his work online from Shapeways. I got one last week. It's the only 3D printed plastic thing I own and strangely probably most futuristic thing I own. 3D printing is part of the future means of production and simply owning a piece of that is interesting enough.

http://www.shapeways.com/blog/archives/822-Theo-Jansens-3D-Printed-Strandbeests.html



The most interesting thing is how people react to it. People can't help but think of it as some kinda of animal-spider-pet. I've had several people demand to know what its name is. The object can't even move on its own and has no face or eyes, so this really surprised me. People seem to somehow relate to the object more than a robotic vacuum or one of those terrible robot puppies they sell at Christmastime.  Often people are just kinda freaked out about it. Its motion is pretty spider-like.

May 21, 2011

Two Techniques in Functional Programming in Mathematica

When I code for customers, I often end up using techniques of functional programming that  many people haven't seen before. This often ends up being problematic, and I've begun to identify the techniques I use that cause the most confusion and explain them when needed. Nevertheless, I use these in my own code because they help in creating well organized, readable code.

There are two techniques in particular that I find the most useful: decorators and closures.

Decorators
I use the term decorator very broadly. For this case, I define a decorator to be a function which takes in a function or a result and instead of using it as input for some other process causes some kind of side effect (it's not a very good definition, but will work here). In Python, decorators are used when defining a function, but I often use the term to apply to higher order functions I wrap around other functions which have some generic usage.  A basic example is a "deprecated" decorator. To test if a function is a decorator, remove it from your code. It shouldn't really affect the core computations of your program. Decorators aren't really aren't integral to a  program. They simply decorate. A decorator should also be modular -- it shouldn't  be built to work with a specific function, but should be able to be used generally across many different functions.

This example of a decorator is used to mark functions as having been deprecated.

deprecated[function_] := 
    Function[args, 
        Module[{}, Print["This function has been deprecated"]; 
        function[args]]
    ]
We can then simply use this when defining functions to give them a deprecation warning.
test = deprecated@
   Function[x, x + 1];
When test is ran now, it will warn that it is deprecated. The decorator could be used on pretty much any function definition. More advanced versions are possible. This version allows us to customize the deprecation message:
deprecated[replacement_?StringQ] :=  
    Function[function, Function[args,
        Module[{},
                            Print["This function has been replaced by "<> replacement];  
              function[args]]   
        ]]


Which can be used like:
test = deprecated["blarg"]@
   Function[x, x + 1];

test[1]
This function has been replaced by blarg
Closures
Closures should be recognizable to anyone who knows functional programming. They provide a nice way to have state in a language without really explicitly mentioning state. Here is a really simple example in Mathematica:
 makeCounter[] := Module[{count = 0}, Function[{}, count++]];
counter = makeCounter[]; 
counter[]
1
counter[]
2
....
Counter is a function which has a state because it references a variable in its parent function makeCounter.  This is cleaner than creating a global variable to hold the global count. The value of counter can only be properly accessed by using counter as we have intended it. I can't give a full treatment of closures and their uses here, but I hope this gives a good idea of what they are.

Combining them
I've used the both closures and decorators together with great synergy in a number of tasks. For example, let's say we want a good way to keeping track of how many times certain functions have been called. We can make a closure which returns a pair: a function to be used as a decorator on functions which are to increment the counter and a function to access the value of the counter. For example:
makeCounterSystem[] := Module[{count = 0}   
    {Function[result, count++; result],Function[{}, count]}];

{counts, totalCount} = makeCounterSystem[];
counts@ Sin[RandomReal[]] ;
totalCount[]
1
This decorator here is different from the previous ones in that it decorates functions not where they are defined, but where they are ran. This can be modified to be a decorator on the definition of the function easily if needed. Whenever we call a function which has counts@ preppended to it, the count will incremented and can then be access by calling totalCount[].

There are numerous uses for this kind of combination. A common use is to keep a log of the results of a function silently:
makeLoggingSystem[] := Module[{log = {}},
  {Function[function, Function[args,  
                Module[{output=function[args]},
              AppendTo[log,output]; output]]],
           Function[{}, log]
     }
     ];


{logger, getLog} = makeLoggingSystem[];
test = logger@
   Function[x, N@Sin[x^2]];
Now whenever we call test, the resulting value is secretly logged and the entire history of the output of the function and any other function decorated by logger is accessible by running getLog[].