Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any advantage to using pow(x,2) instead of x*x, with x double?

is there any advantage to using this code

double x; double square = pow(x,2); 

instead of this?

double x; double square = x*x; 

I prefer x*x and looking at my implementation (Microsoft) I find no advantages in pow because x*x is simpler than pow for the particular square case.

Is there any particular case where pow is superior?

like image 546
Alessandro Jacopson Avatar asked Jun 12 '11 09:06

Alessandro Jacopson


People also ask

Is x * x faster than POW X 2?

x*x or x*x*x will be faster than pow , since pow must deal with the general case, whereas x*x is specific. Also, you can elide the function call and suchlike.

Is C++ POW fast?

YES! Very fast if you only need 'y'/'n' as a long/int which allows you to avoid the slow FPU FSCALE function.

What is the correct prototype of power function?

C pow() Prototype To find the power of int or a float variable, you can explicitly convert the type to double using cast operator. int base = 3; int power = 5; pow(double(base), double(power));


1 Answers

FWIW, with gcc-4.2 on MacOS X 10.6 and -O3 compiler flags,

x = x * x; 

and

y = pow(y, 2); 

result in the same assembly code:

#include <cmath>  void test(double& x, double& y) {         x = x * x;         y = pow(y, 2); } 

Assembles to:

    pushq   %rbp     movq    %rsp, %rbp     movsd   (%rdi), %xmm0     mulsd   %xmm0, %xmm0     movsd   %xmm0, (%rdi)     movsd   (%rsi), %xmm0     mulsd   %xmm0, %xmm0     movsd   %xmm0, (%rsi)     leave     ret 

So as long as you're using a decent compiler, write whichever makes more sense to your application, but consider that pow(x, 2) can never be more optimal than the plain multiplication.

like image 197
Alnitak Avatar answered Sep 18 '22 19:09

Alnitak