Why is this necessary?


What would be the point of taking time to import a square root function when anyone that has a basic grasp on algebra could be able to simply take their number to a .5?

my point:
25**.5 = 5
sqrt(25) = 6


The real question is why not? A Math module would be incomplete without the function. Not only that, the module is already compiled so will run much faster when given thousands or even millions of square roots to calculate.

From a readability standpoint, it also makes sense to use a built-in function.

def hypotenuse(a,b):
    return sqrt(pow(a, 2) + pow(b, 2))

This function could be run many times on any number of right triangles with known sides.

def side(a, h):
    return sqrt(pow(h, 2) - pow(a, 2))

Likewise, we can run this on millions of triangles with known hypotenuse and one side.


Just complementing what @mtf said about the sqrt() and **.
Which is faster in Python: x**.5 or math.sqrt(x)? - StackOverflow

It's worth reading in case you get interviewed and they ask you this :slight_smile:


I am not an expert Python programmer (or even a competent novice) so I cannot say with any certainty that this is true, but my understanding is that Python script is fully compiled at runtime, then it runs.

JavaScript, on the other hand is never compiled at runtime. Declared variables and functions are hoisted on the first pass of the interpreter, then on the second pass, lines are compiled as they are run, with possibly some caching of compiled code inside loops. Because it runs this way, anything that is pre-compiled is going to run much faster.

My answer above is not "official" but I'll still stand by it, until someone tells me different. (I don't mind being corrected, btw.)


D'oh! I just realized this was a Python question, and here I am talking JavaScript. Fixed my post above. As the page that @g4be reflects, the built-in is ~19% faster than the written expression, but for a small program with not many iterations, the speed difference is hardly negligible.