I’m a self taught developer (about 3 years now), and I want to improve my development skills by learning how to write math equations into code.
It’s something that continues to bother me, I see many books and articles accompanied by glowing math equations, which genuinely look really interesting. I can read parts of them (multiplication, division, decimals, sigma, variables) but I have troubles when going off to implement them in code.
For example, how would one go about getting started to understand these kind of equations: http://en.wikipedia.org/wiki/Manhattan_distance and going off to write them in code?
Any recommendations of places to get started? Is it not the code issue, but lack of fundamental math understanding? I’m willing to listen and read, since I feel this ability is really important for a developer to have.
Well, the crucial thing I guess is that you need to be able to break down the formula you’re interested into its component pieces, and if you can understand how to code those pieces individually, you are in a position to then glue them back together in the form of code.
Let us take as an example the Manhattan distance between two points in two-dimensional space with a fixed
(x, y)coordinate system. You want to write a function that will take two points and give you the Manhattan distance between those points. Let’s forgo the use of object-oriented concepts here and just assume that you have four input variables:So our function will be like
What should the insides of the function (the function body) look like? Now we inspect the mathematical formula that we want to rewrite as code. Wikipedia’s version (under “Formal description”) treats the case of arbitrary dimensions – we can do this too, but for now we’re considering the 2-dimensional case only. So their
nis 2 as far as we are concerned, and we want to compute|x1 - x2| + |y1 - y2|. That is the result of losing the sigma notation in favour of an expression describing a sum with two summands. But we still haven’t worked out how|a - b|can be expressed in computer code.So now the function could look like
And that, as far as it goes, is fine, because we’ve isolated the thing we don’t yet know how to do as another function, called
bars(). Once we definebars(), the functionmdistance()will work just fine, assuming of course that our definition forbars()is sensible. So the problem is just to definebars(). By breaking the problem into its component parts, we’ve made our job easier, because we just have to make each part work – which is simpler than making everything work at once.So how should
bars()be defined? Well,|a - b|just expresses the idea “the absolute value ofa - b“. PHP has a built-in function for the absolute value of a real number; it isabs(). So we definebars()like this:Now our function
mdistance()will work just the way we want.