Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between sqrt(x) and pow(x,0.5) [closed]

Tags:

c++

c

sqrt

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?

like image 546
Alex Avatar asked Jul 02 '13 04:07

Alex


People also ask

Is sqrt faster than pow?

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) .

How do you use the pow function?

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.

What does math Pow do in Javascript?

The Math. pow() method returns the value of x to the power of y (xy).

Is it possible to find the square root of a number using the Math pow () function?

Using Math. pow to find the square of a number, we can use it to find the square root of a number as well.


2 Answers

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.

like image 75
banarun Avatar answered Oct 15 '22 19:10

banarun


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.

like image 43
vroomfondel Avatar answered Oct 15 '22 19:10

vroomfondel