Ravings and musings from a traveller who might be wrong...
Give meaning to a probably meaningless existence.
Monday, September 12, 2011
What else would you do?
Sunday, May 15, 2011
Spell Checkers are the best spelling teachers.
Has been learning spelling from her for years nwo.
Image from here.
Parallels have inconsistent systems.
Thursday, May 12, 2011
How to kill a child.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> int main() { pid_t pid = fork(); if (pid == 0) { printf("Killing the child using with next line."); _exit(0); } else if (pid > 0) { printf("While we're at it, might as well kill the parent as well"); exit(0); } }
Monday, May 9, 2011
A lame joke.
Friday, April 29, 2011
Crying babies behind you.
Harmonic mean
Mathematics
This post is going to be about another form of average, called the harmonic mean and this is found using the following formula:It may look a bit complex at first, but really, it's not.
Say we want to find the arithmetic mean of the the following numbers 5, 2, 4, 10. Let's start by taking care of the denominator of the formula first:
As you now know, that's a summation over the reciprocals of our numbers:
We're not ready yet though because that's only half of the formula. So, now we ended up with this complex fraction:
Now we simplify that complex fraction by multiplying the numerator by the reciprocal of the denominator:
Therefore we can say that 'the harmonic mean is the reciprocal of the arithmetic mean of the reciprocals' [Wikipedia].
Programming
Now let's write our harmonic mean function in JavaScript:var harmonic = function (numbers) { var length = numbers.length, denominator = 0, i = 0; for (; i < length; ++i) { denominator += 1 / +numbers[i]; } return length / denominator; }; harmonic([5,2,4,10]); // 3.8095238095238093
Arithmetic mean
Mathematics
Since now you're already familiar with the summation notation, I'm going to start this post with this:The arithmetic mean is most commonly referred to as just the average, although it's just one of several ways of calculating an average...and it's probably the one you're most familiar with.
Let's say we have these five numbers 1, 4, 7, 5, 8 and we want to find their arithmetic mean:
Therefore if we use x for our arithmetic mean, we can represent that as:
Programming
Writing a function for calculating the arithmetic mean in JavaScript shouldn't be too difficult:var average = function (numbers) { var sum = 0, i = 0, j = numbers.length; for (; i < j; ++i) { sum += +numbers[i]; } return sum / j; }; average([1,4,7,5,8]); // 5
Highlighting my code with some rays of Sunlight.
It's what I am currently using for this blog. Tommy Montgomery, I salute you.
Here's an example:
/** * jQuery plugin for Sunlight http://sunlightjs.com/ * * (c) 2011 Tommy Montgomery http://tommymontgomery.com/ * licensed under WTFPL http://sam.zoy.org/wtfpl/ */ (function($, window, undefined){ $.fn.sunlight = function(options) { var highlighter = new window.Sunlight.Highlighter(options); this.each(function() { highlighter.highlightNode(this); }); return this; }; }(jQuery, window));
Huh, it's highlighting itself.
The Σ notation.
Mathematics
In this one, I will talk a bit about the Capital Sigma notation:
You will probably see it being used as follows:
This is actually part of the ~third diagram you will see on its Wikipedia page.
What does it all mean? Here, n represents the upper bound of the summation, m is the lower bound of the summation and i is the index of the summation.
Let's now look at the complete Wikipedia diagram via some inline linking:
As you may have now guessed, the Σ is used to represent a summation (i.e. using addition) over a list of numbers (and other addable entities). The xi represents how the sequence should be formed, replacing the i with the current value of i in the present iteration.
Now it should be more clear as to what the upper/lower bounds mean. The upper bound n refers to when the sum should 'end' and m is used to represent where to 'start' the sum.
My terminology in the previous paragraph may be slightly incorrect, especially the part about start/end, so be weary.
If you've managed to get that, here's a more concrete example:
And another one:
You could have probably calculated the above in your head, but what if I gave you the following:
Can you find the sum of the numbers in the range 1 ≤ i ≤ 50 mentally? Fortunately, you don't have to because there is a formula you can use for that particular sequence of numbers:
So going back to the previous problem with the 50, we can now plug in the upper bound into the formula:
Therefore:
Let's get a bit more concrete. Say you have some coins running around and you form a triangle with them:
Without individually counting them, can you tell me the total number of coins that are currently forming the triangle? Or better yet, what if you added the fifth row...how many coins would there be then?
Simple, just use the formula. Let's find out how many coins would there be if we added the fifth row.
First we'll start by representing our problem in math notation which in this case is easy because the pattern is very trivial:
And now, the formula:
So if we add a fifth row, we would get a total of 15 coins:
How about this one?
Well thankfully, mathematicians also have a formula for that (and many others):
So, applying that to our latest problem, we get:
Therefore:
Programming
Now, some programming shall we? I will use JavaScript because I like it (talk about one hammer...well it's not the only one) although I have to admit that a solution written in a purely functional programming language like Haskell would have been much more elegant.
Now let's start applying this function to work out some summations, starting with the first one I talked about:
We can write something like this to workout the problems given with that pattern:
var simpleSum = function(upper) { return (upper * (upper + 1)) / 2; };
What about the next one?
Something like this could work:
var squaredSum = function(upper) { var numerator = upper * (upper + 1) * (2 * upper + 1), denominator = 6; return numerator / denominator; };
But do we have to keep creating a new function for every pattern we need? Surely not!
We can write a function that does something like this:
If you're worried about the stack, you can use a for loop:
var sum = function (pattern, lower, upper) { var s = 0; for (; lower <= upper; ++lower) { s += pattern(lower, upper); } return s; };
But you can also use recursion to create a more elegant solution:
var sum = function(pattern, lower, upper) { if (lower > upper) return 0; return pattern(lower, upper) + sum(lower + 1, upper, pattern); };
As you can see, I kept it as concise as possible; I even didn't bother to add curly brackets for the if-construct. If you're hardcore on making slightly-less readable code, you can even remove that if-construct and check for the condition using the ternary operator.
I also added the possibility to start from a specified number given by the lower variable. The generic function comes with a price though, as everything does. The problem now is that we've transformed an algorithm of O(1) to one with O(n).
I will not go much into algorithm complexity in this post but basically with our previous 'simpler' functions, the execution time of the function depended mainly on how complex our formula was since all it's operation run in constant time, whereas with the new generic function, we will take a big performance hit because execution time depends mainly on the range of numbers we specify i.e. the bigger the range, the more time the function will take to return a result.
Another way to say this would be that the execution time scales proportionally to the number of elements in the specified range m...n.
Let us now apply the last function to create the previous two patterns:
var m = 1, n = 5; sum(function (i) { return i; }, m, n); sum(function (i) { return i * i }, m, n);
Now we can also write something like this:
sum(function(i) { return Math.pow(i, 5); }, m, n);
If we wanted to write it using the O(1) algorithm, we would have had to turn the formula into JavaScript instead of using the i5. But, we can even up the ante a bit and make all of this even cooler and that's where partial function application will come in to do the job. This is the partial function we will use:
var partial = function(func) { var args = Array.prototype.slice.call(arguments).splice(1); return function() { var allArguments = args.concat(Array.prototype.slice.call(arguments)); return func.apply(this, allArguments); }; };
I have already talked about partial function application for JavaScript in the other one so I won't go into any details here, but I will show you how we can use it to produce functions that have a smaller arity (number of arguments):
var simpleSum = partial(sum, function (i) { return i; }), squaredSum = partial(sum, function (i) { return i*i;});
In our current case, we reduced the arity of sum to produce functions that only require the lower and upper bounds since the pattern function will already be stored in the closure produced by the partial function. Usage is then simple:
simpleSum(1,5); // 15 squaredSum(1,5); // 55
Thursday, April 28, 2011
Wednesday, April 27, 2011
Gervais, Merchant and especially Pilkington.
Do you panic when you see some math?
If you're mathematically inclined, I suggest you avoid reading these posts because they will probably insult your intelligence.
I basically plan to write a little bit about some stuff which I'm currently learning about on my own. That's also a warning for you: I'm learning this stuff as I go (and by myself).
This means that there could be mistakes in what I write, and there probably will be...so tread lightly on it. And if you actually read this stuff, and find mistakes, I truly appreciate if you contact me via comments or whatever about them because I'm still learning about these concepts.
The main reason I will be writing these posts (and having this blog in the first place) is for my own amusement, so I can laugh back in the future. Seriously though, writing about what I'm learning helps me more in understanding because of the research and thinking I do while working on the actual writing. Sort of like my semi-personal notes.
So yea, I think my first post will be about the sigma notation.
Also, I tend to use both math and programming terms for most of the stuff, including (usually incorrectly) mixing both math and programming notations together; yea, that's one thing I'm working on learning more about because usually I know how to explain something using programming terminology, but not using math notation. So for the mathematically abled, I apologize; once again, I appreciate the corrections you can make.
Oh and another thing which I should have mentioned in an earlier post. To render the math in this blog, I'm using CodeCogs' online equation editor.
Scooby Doo
Tuesday, April 26, 2011
The pope.
Razing a raise.
The irony here is that the former means to level (tear down to the ground) and the latter is all about elevation.
Monday, April 25, 2011
Everyone.
Every person who makes a sweeping generalization is wrong.
Surviving in an office.
Learn to talk and type in C0rp0ratE Speak.
Drugs also help.
Madness!
You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the nerves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege̿̔̉x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the trangession of a chi͡ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of regex parsers for HTML will instantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection will devour your HTML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fight he com̡e̶s, ̕h̵is un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂̈́ghtenment, HTML tags lea͠ki̧n͘g fr̶ǫm ̡yo͟ur eye͢s̸ ̛l̕ik͏e liquid pain, the song of re̸gular expression parsing will extinguish the voices of mortal man from the sphere I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful the final snuf
fing of the lies of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL IS LOST the pon̷y he comes he c̶̮omes he comes the ichor permeates all MY FACE MY FACE ᵒh god no NO NOO̼OO NΘ stop the an*̶͑̾̾̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e
not rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ
Have you tried using an XML parser instead?
Been there, done that.
Why, you might ask? Same reason I asked this question.