Wednesday, August 24, 2011

The Creators

Consider the following syllogism:

Everything that exists has a creator.
God exists.
Therefore God has a creator.

Now, this is clearly valid from a purely deductive point of view. But deduction is nothing more than the mechanical rearrangement of symbols, hence it prove nothing about the true state of affairs in our universe until one considers the premises.

First consider "Everything that exists has a creator". If you accept this as a universal truth than we can move on. If you don't then you can entertain the thought that somethings exist and have no creator. Let's revisit the idea a bit later.

No consider the premise "God exists". If you are a believer than you hold this premis as true, by definition. But, if you also hold the first premise true, then you are logically bound to admit God was created by some prior God and so on ad infinitum. But clearly, this is not in line with the teachings of any mainstream religion. So as, say a Christian, you are forced to deny that everything that exists has a creator. Indeed, Christians would argue that everything that exists has a creator EXCEPT God.

So the rather than presupposing that "the universe always existed" or "some universe always existed", Christians belive in an all powerful, all knowing entity that exists and has no creator. I find that incredulous and any reasonable person should as well.

Personally, it seems obvious that both premises above are false. There are many things that exist and have no creator (but God is not one of them).

All this aside, if you are mathematically literate, enjoy physics and worry about matters of what can exist without having a creator I highly recommend The Fallacy of Fine-Tuning: Why the Universe Is Not Designed for Us by Victor J. Stenger.

Saturday, August 6, 2011

Dashed Lines in HTML5 Canvas

There is a lot of functionality missing from the Canvas API. One obvious facility is support for dashed lines. Here is the start of some dashed line code I am working on as part of a larger project. It is not fully tested yet so caveat emptor. I started with code I found here and attempted to make it more efficient by taking most of the math out of the main loop.


var initDashing = function(ctx) {
if (!ctx.dashLine) {
ctx.dashStyle=[3,2] ;
ctx.dashedLine = function(x1,y1,x2,y2) {
var dashStyle = ctx.dashStyle,
dashCount = dashStyle.length,
sign = x2>=x1 ? 1 : -1,
dx = x2-x1,
dy = y2-y1,
m = dy/dx,
xsteps = dashStyle.map(function(len){return sign*Math.sqrt((len*len)/(1 + (m*m)));}),
dRem = Math.sqrt( dx*dx + dy*dy ),
dIndex=0,
draw=true;
this.moveTo(x1,y1) ;
while (dRem>=0.1){
var dLen = dashStyle[dIndex],
xStep = xsteps[dIndex];
if (dLen > dRem) {
xStep = Math.sqrt(dRem*dRem/(1+m*m));
}
x1 += xStep ;
y1 += m*xStep;
this[draw ? 'lineTo' : 'moveTo'](x1,y1);
dRem -= dLen;
draw = !draw;
dIndex = (dIndex+1) % dashCount ;
}
};
};
};


Here are some examples of usage (here I am using the Jasmine unit testing framework)



describe("Dashing", function() {
it("draws a 3-2 dashed line by default", function(){
var ctx = document.getElementById('test1').getContext("2d");
ctx.strokeStyle = "black" ;
initDashing(ctx) ;
ctx.beginPath() ;
ctx.dashedLine(0,0,100,100) ;
ctx.closePath();
ctx.stroke();
});

it("draws a 10-5 dashed line", function(){
var ctx = document.getElementById('test2').getContext("2d");
ctx.strokeStyle = "black" ;
initDashing(ctx) ;
ctx.dashStyle = [10,5] ;
ctx.beginPath() ;
ctx.dashedLine(0,0,100,100) ;
ctx.closePath();
ctx.stroke();
});

it("draws a 10-5-2-5 dashed line", function(){
var ctx = document.getElementById('test3').getContext("2d");
ctx.strokeStyle = "black" ;
initDashing(ctx) ;
ctx.dashStyle = [10,5,2,5] ;
ctx.beginPath() ;
ctx.dashedLine(0,0,100,100) ;
ctx.closePath();
ctx.stroke();
});

it("draws a 10-5-3-4 dashed line", function(){
var ctx = document.getElementById('test4').getContext("2d");
ctx.strokeStyle = "black" ;
initDashing(ctx) ;
ctx.dashStyle = [10,5,3,4] ;
ctx.beginPath() ;
ctx.dashedLine(100,13,0,80) ;
ctx.closePath();
ctx.stroke();
});
});







I still have to implement a dashed version of arc, encapsulate better and test this code much more thoroughly. I'll upload to git hub when it is ready.

Sunday, June 5, 2011

On the Goodness of Programming Languages

Since my last post on C I have been thinking a lot about what makes a programming language good. This is also motivated by my recent emersion into JavaScript that has me wondering how good of a language is JavaScript. I've had similar thoughts about C++, Java, Lisp and others in the past.

I think that the only sensible conclusion is there is no way to measure the goodness of a language in any objective way. I am certain that I can can come up with a metric that would declare C as the best language ever developed, and another that would make the winner Lisp, or Mathematica or JavaScript. For example if, to simplify things a bit, I decide that the metric for a language's goodness is that:
  1. It be functional (first class functions, closures, etc.)
  2. It be ubiquitous (available on almost every computing device)

Then it is clear that JavaScript is the best language ever. I can also easily derive a metric that would declare Mathematica as the best language ever (and on some days I am convinced of the absolute truth of this!).

But the truth is that there can never be the best language ever. This is not because programming language technology is constantly (or at least in fits and starts) evolving. The reason there can never be a best programming language begins with the idea of Turing Completeness but it does not end there. Any language worth learning is TC and by that metric is no better than any other. Yet, it is often argued that some languages are more expressive than others (e.g. Lisp is more expressive than Fortran) and therefore one can solve a wider class of problems faster in Lisp than Fortran. But that does not mean there are not valid metrics by which Fortran can be declared the world champion of programming languages.

Humans spend a way too much time debating what the best is. What is the best car, best restaurant, best sport, best OS and best programming language? We do this because we want to be associated with the best. I drive an X, X is the best, therefore I have superior taste. For programming languages such arguments are silly not because we each have our own tastes. They are silly because if you are a programmer and don't sometimes see the superiority of Language A over Language B (and visa versa) then my guess is you are a rank amateur (or really boring person to sit next to at the office). So next time you find yourself in one of those "my language is better than yours" debates (and I've been there too) stop yourself, pick up the best editor :-) and write some code instead!


Saturday, May 21, 2011

The Joy of C

My latest assignment at work is to write a very fast message journal. Basically this is a way for writers to stream FIX messages (but could be anything) into a file while at the same time having one or more readers receive the messages. There are numerous little details I am leaving out but they are not important to the point I wish to make.

The programmers who wanted this journal asked me to write it in C rather than C++. Although I usually prefer C++ there was no compelling reason that C++ was needed. To my surprise, I rather enjoyed writing it in straight C and in fact, I am pretty sure the end result is a lot less complex than it would have been in C++.

Don't get me wrong. I am still a fan of OO but the attitude that anything OO is apriori better than pure procedural is a crock of poo. Programming in C forces you to be economical. There is no fancy data structures, templates or virtual functions. There is no Boost or meta-programming. You basically get arrays, macros and some straightforward libraries for threading, I/O and string manipulation. And for many more problems than you might expect, this is all you need.

In C (well written C anyway), you can almost always look at a piece of code and see by inspection exactly what will happen. In OO languages, with virtual functions, this is rarely the case. When you see p->f() in C++ you need to consider p's type and all classes derived from it to imagine everything that might happen. This often incurs a high cognitive load on maintainers of the code. Of course, with function pointers you can create equally obscure C, but you need to work harder in C so you only do that when there is a good reason. C forces you to keep your eye on the ball.

Now, in defense of C++, I have to say that programming in C++ has actually prepared me to be a better C programmer. For example, I treated all my structs as if they were private and wrote interfaces so users of my API never needed to know the internal workings of theses structs. In fact, most of my structs were hidden in private headers or in the .c files themselves. Most of my implementation functions were statics and hence private. This gave me the flexibility to change the internals without breaking user code. OO taught me to think this way. OO also taught me to think about writing code that can be unit tested and to write the tests right after the interfaces were specified but before the implementation. I brought this discipline to C as well.

The one thing truly lacking in C is exceptions. I have to say that exception handling and RAII are two of C++'s strengths. However, with discipline, you can do without these as well.

So if you ever find yourself forced back into a ancient language like C, don't fret. Take the concepts you learned in more modern languages and think about how you can uses the spirit of those concepts to write better code. You just might enjoy going retro!

Saturday, May 7, 2011

End to End JavaScript with Node and HTML5

This is my latest book project. In this book I will build a online multi-player poker game application entirely in JavaScript using Node.js on the server and JQuery+HTML5 Canvas on the client. The book will also feature MongoDB and Jasmine.

The main emphasis of the book is to illustrate test driven development of a non-trivial client-server JavaScript application. Although the book subject matter is a game, there will be lots of valuable take-aways for JavaScript, Node and Canvas developers.

Saturday, July 10, 2010

Mathematica Cookbook Attacked by a Troll: Jon Harrop

Recently I have had a very unpleasant experience with a known internet troll who has been attacking Mathematica Cookbook on the amazon.co.uk site. I posted the following review on amazon.co.uk by way of defending myself and my work. They may or may not allow it but I wanted to share it with you....


I would like to direct UK customers who may be interested in my book to a few facts.

1) Both of the previous reviewers (Edward and Jon Harrop) are actually the same person. I have very strong evidence this is the case. You may email me at mathematicacookbook@gmail.com if you want the details.

2) Jon Harrop is author of "F# for scientists" and about 2 years ago I blogged unfavorably about Mr. Harrop's book. You can see my comments here: .

3) Apparently I hurt Jon's feelings so badly that he could not wait to order my book just to give it a poor review. In fact, he has given it two!

4) Since then he has been using my own book as inspiration for several of his own blog posts so apparently he does not find it totally useless.

5) If you would like to see a more balanced treatment of my book please see these reviews: http://amzn.to/cKxJVh, http://oreil.ly/9ypIlX, http://bit.ly/b6HqFS and http://amzn.to/bQSr6Y.

6) I won't comment further on Mr. Harrops character because I think his actions speak for themselves. The interested reader can google "Jon Harrop Troll" and draw their own conclusions.

7) Finally, my book is not perfect. But I absolutely did not plagiarize anyone and link extensively to others work where they inspired my codes. I have been correcting issues as they are found and the O’Reilly site is where errata can be found. I think may readers in the UK who are fans of Mathematica can find a lot of value in my book and I don't want the bitter feelings of one individual to scare you away.

Tuesday, July 6, 2010

The Elegance of Rule-Based Programming in Mathematica


Not too long ago I had to take a programming test as part of the application process for a development position at a hedge fund. The test had two problems - one easy and one not so easy. The solutions to both problems had to be implemented in your choice of Java, C or C++. You had two hours to finish.


I have never been good at presure cooker coding tests like this. I personally don't think these kind of tests bring out the best in most developers but there are some good devlopers who work well under these conditions. I just am not one of them.


In any case I recently thought of the hard problem on this test and how trivial it would be to solve in Mathematica. Indeed I whipped up and tested this solution on my train ride home which is only about 45 mins!


The solution is very short and I am guessing is much shorter than the average solution you can find in Java or C in the equivalent amount of time. The brevity come form exploiting mathematica's powerful rule-based approach. Most of the code is comments!


Problem



A collection of particles is contained in a linear chamber. They all have the same speed, but some are headed toward the right and others are headed toward the left. These particles can pass through each other without disturbing the motion of the particles, so all the particles will leave the chamber relatively quickly.


You will be given the initial conditions by a string containing at each position an 'L' for a leftward moving particle, an 'R' for a rightward moving particle, or a '.' for an empty location. Initially, no location in the chamber contains two particles passing through each other.


Create an animation of the process. At each unit of time, you want a string showing occupied locations with an 'X' and unoccupied locations with a '.'. Create code that for a function animate that is given an integer speed and a string giving the initial conditions. The speed is the number of positions each particle moves in one time unit.


The function will return a list of strings in which each successive element shows the occupied locations at the next time unit. The first element of the return should show the occupied locations at the initial instant (at time = 0) in the 'X', '.' format. The last element in the return should show the empty chamber at the first time that it becomes empty.


Solution




ClearAll[simulation, step, L, R, r, l, rule1, rule2, rule3, animation];

(*
This function does most of the work. It simulates a single step in the animation.
It uses 3 rules which are initialized in the calling function and are visble
here via the dynamic scoping of Block.

There are 3 transformations performed within a Do. The Do's role is to run the
transformations velocity times as a means for making the particles move
that many steps.

The first transform takes the input and adds an empty cell to the start and end of the chamber.
This is done to avoid having special rules to deal with the
boundary conditions at the end of the chamber.

The second transformation uses rules that are applied repeatedly using ReplaceAll (//.).
I discuss the rules below.

Delete is used to remove the dummy empty cells added in the first step and
a third transformation maps lower case r and l back to upper case before the Do
repeats.

*)
step[chamber_List, velocity_Integer] := Module[{work = chamber},
Do[
work =
Delete[work /. {P__} :> {{}, P, {}} //. {rule1, rule2,
rule3}, {{-1}, {1}}] /. {r -> R, l -> L}, {velocity}];
work
]

(*
The simulation sets up 3 rules. It is not necessary to define the rules here in a
Block. The code is written this way largely because I incrementally developed the
rules in the global scope and grafted them into a program later on.

rule1 is responsible for moving a R partcle to the Right. NOTE: When a particle moves
I change its case from upper to lower to make it invisble to subsequent rules.

rule2 is responsible for handling an intermediate condition where a right moving
particle lands in a cell of another right moving particle that has not moved yet.

rule3 deals with left moving particles being careful to also handle the case where a
previously moved partcle Z may be in the same cell as the L.

The hardest aspect of this solution was distilling the transformations down to these
three rules. It took some trial and error. It is possible I missed some corner case
so let me know if you see a bug!!

The idea here is that FixedPointList drives the simulation until it reaches a steady
state and Most removes the repetitive last entry.

A final transformation maps particles to "X" as dicated by the specifications.
*)

simulation[chamber_List, velocity_Integer] :=
Block[
{rule1 = {X___, {R}, {P___}, Y___} :> {X, {}, {P, r}, Y} ,
rule2 = {X___, {R | r, r}, {P___}, Y___} :> {X, {r}, {P, r}, Y},
rule3 = {X___, {P___}, {L, Z___}, Y___} :> {X, {l, P}, {Z}, Y} },
Most[FixedPointList[
step[#, velocity] &, chamber]] //. {{(L | R) ..} -> "X", {} ->
"."}
]

(*
The main function does little but convert from the string encoding specified by the problem to a more convenent symbolic form where each position in the chamber is one of {L}, {R} or {} for empty and the chamber itself is a list rather than a string.
*)

animation[chamber_String, velocity_Integer] :=
simulation[
(Characters[chamber] //. {"." -> {}, a_String :> {Symbol[a]}}),
velocity]



The Test Cases




1) The single particle starts at the 3rd position, moves to the 5th, then 7th, and then out of the chamber.
In[360]:= animation["..R....",2]//Grid
Out[360]=
..X....
....X..
......X
.......

2) At time 1, there are actually 4 particles in the chamber, but two are passing through each other at the 4th position.

In[361]:= animation["RR..LRL",3]//Grid
Out[361]=
XX..XXX
.X.XX..
X.....X
.......


3) At time 0 there are 8 particles. At time 1, there are still 6 particles, but only 4 positions are occupied since particles are passing through each other.


In[362]:= animation["LRLR.LRLR",2]//Grid
Out[362]=
XXXX.XXXX
X..X.X..X
.X.X.X.X.
.X.....X.
.........


4) These particles are moving so fast that they all exit the chamber by time 1.
In[363]:= animation["RLRLRLRLRL",10]//Grid
Out[363]=
XXXXXXXXXX
..........

5) The empty chamber test

In[364]:= animation["...",1]//Grid
Out[364]=
...

6) A complicated test

In[365]:= animation["LRRL.LR.LRR.R.LRRL.",1]//Grid
Out[365]=
XXXX.XX.XXX.X.XXXX.
..XXX..X..XX.X..XX.
.X.XX.X.X..XX.XX.XX
X.X.XX...X.XXXXX..X
.X..XXX...X..XX.X..
X..X..XX.X.XX.XX.X.
..X....XX..XX..XX.X
.X.....XXXX..X..XX.
X.....X..XX...X..XX
.....X..X.XX...X..X
....X..X...XX...X..
...X..X.....XX...X.
..X..X.......XX...X
.X..X.........XX...
X..X...........XX..
..X.............XX.
.X...............XX
X.................X
...................




I'll post the Mathematica Notebook on MathematicaCookbook.com