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?
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.
YES! Very fast if you only need 'y'/'n' as a long/int which allows you to avoid the slow FPU FSCALE 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));
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.
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