The difference between sqrt (x) and pow (x, 0.5)

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

pow(x,0.5); 

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

+7
c ++ c sqrt
source share
3 answers

I checked the test to test the performance of sqrt(x) and pow(x,0.5)

one.

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

2.

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

1st place took about 20 seconds, when on my computer 2 seconds took about 2 seconds. Thus, performance is much better. Like others, the readability already mentioned is another reason.

+10
source share

Of course, if you only think about mathematical equivalence ...

But in terms of algorithms to calculate the result, sqrt specific to one thing, while pow is general.

So, you could (fairly) assume that you could write a faster function for sqrt than write a generic pow function.

+5
source share

I remember reading somewhere that sqrt () is a special case, which is guaranteed by the correct rounding of the IEEE specification. I will see what to find the source. It should be a little faster because it should only handle one case.

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

Edit: According to IEEE-754, it is assumed that both the pow () function and sqrt () should be implemented in such a way that the rounded value represents the closest possible floating point representation to the real value. However, sqrt () should be faster.

+5
source share

All Articles