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?
With regard to C standard library sqrt and pow , the answer is no. First, if pow(x, . 5f) were faster than an implementation of sqrt(x) , the engineer assigned to maintain sqrt would replace the implementation with pow(x, . 5f) .
pow() is function to get the power of a number, but we have to use #include<math. h> in c/c++ to use that pow() function. then two numbers are passed. Example – pow(4 , 2); Then we will get the result as 4^2, which is 16.
The Math. pow() method returns the value of x to the power of y (xy).
Using Math. pow to find the square of a number, we can use it to find the square root of a number as well.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With