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

馋奶兔 提交于 2019-12-08 17:11:10

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/17417490/difference-between-sqrtx-and-powx-0-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!