Wednesday, January 26, 2011

Most useless skills ever aka how to implement sqrt() in javascript.

Couple of day ago, Dominic Szablewski, author of Impact Engine tweets about interesting job interview:

Seriously, WTF? Why Javascript developer, even working for such a big company as Facebook, needs to know how to re-implement build-in language elements? Knowing everything about everything was bane of elementary education - we have all been trained (at least here, in Eastern Europe), that when we need to know something we shouldn't use 'outside' sources such as books then and Internet now. Why? Personally, I didn't know any developer who didn't sometimes read the documentation, especially if it takes less than 3s if you know what you are looking for.
In case that 'implementing sqrt()' task will ever occurs again, here are two of my JS implementations:) :
//in this way calculators implements square roots:
var ownSqrt = function(number) {
    return Math.exp(Math.log(number)/2);
}
But if it is forbidden to use Javascript Math object constants at all, the best way is to use approximation like this:
var ownSqrt2 = function(number) {
    var x = number;
    while (Math.abs(x*x-number) > 0.001) x = (x*x+number)/(2*x);
    return x;
}
There are a lot of different algorithms on Wiki, and their implementations all over the Web.

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Bahaha. I like the first implementation, especially since it's just a mathematical obfuscation of Math.pow(x, .5) xD

    ReplyDelete
  3. Of course it is - programming is all about cheating, isn't it:)?

    ReplyDelete
  4. It's a trick question. You would NEVER implement Math.sqrt() in javascript, since the existing Math methods are at a compiled level of javascript which is done at a speed that javascript could never match.

    ReplyDelete
  5. Thanks for such a great blog here. I was searching for something like this for quite a long time and at last, I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.
    artificial intelligence internship | best final year projects for cse | internship certificate online | internship for mba finance students | internship meaning in tamil

    ReplyDelete