Question

I was wondering why there is sqrt() function in C/c++ as we can achieve the same using

pow(x,0.5);

how is sqrt(x) different for pow(x,0.5) . Is there a specific reason of having sqrt function?

Was it helpful?

Solution

I ran a test for you to check the performance of sqrt(x) and pow(x,0.5)

1.

for(int i=0;i<100000000;i++) 
    pow(double(i),0.5);

2.

for(int i=0;i<100000000;i++)
    sqrt(double(i));  

1st one took around 20 seconds where as 2nd one took around 2 seconds on my computer. So performance is way better. As other have already mentioned readability is other reason.

OTHER TIPS

I remember reading somewhere that sqrt() is a special case that is guaranteed by the IEEE specification to be rounded correctly. I'll look that up to find a source. It should be a little faster too, because it only has to handle one case.

Even if they were the same, it's nice to have a builtin alias for a commonly used function!

Edit: According to the IEEE-754, both the pow() function and sqrt() are supposed to be implemented such that the rounded value is the closest possible floating point representation to the real value. However, sqrt() should still be faster.

Sure, if you think of only the mathematical equivalence...

But in terms of algorithms to compute the result, sqrt is specific to one thing whereas pow is generic.

So you could (rightly) assume that it's possible to write a faster function for sqrt than it is to write the generic pow function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top