By John Hyde
In an article on Hex Central, Mike Lewis showed how to calculate the distance between any two British postcodes. Here’s a tip for speeding up the process.
The calculation that Mike demonstrated is a simple application of Pythagoras’ theorem. You start by getting the grid references (that is, the x, y co-ordinates) of the two postcodes. Next, add the sums of the squares of the x and y distances between them. Finally, take the square root of the value thus obtained. That final figure is the straight line distance between the two points.
My tip is simply to omit the calculation of the square root. So, instead of working with the actual distance, you work with the square of that distance.
As an example, let’s suppose you want to sort a series of postcode pairs into descending order of distance apart. You omit the calculation of the square root, which means that you will in fact be sorting by the square of the distance apart. The result will still be correct.
Similarly, if you want to find all postcodes within a given radius of a fixed point, you omit the square root calculation, and compare the distances with the square of the target radius. Again, this will give the correct result.
Since the calculation of the square root is likely to be the most time-consuming part of the process, leaving it out should speed things up considerably.