Unary operator in C or C++ for the second power of a number

346 views Asked by At

Given a double x, it is known that it is more efficient to use x*x instead of pow(x,2). Imagine for simplicity that we have to calculate the square root of x: as it is a unary operation, for this purpose we have sqrt(x). Now, also raising x to the second power is a unary operation, but we have nothing like (as far as I know) pow2(x).

I implemented my own pow2 as:

inline double pow2(double a){return a*a;}

which should be still better than pow(a,2), but it is based on the * operator that is not unary. How to implement a genuine unary implementation of pow2? Would it be the most efficient way to obtain the second power of a double?

NOTE: I am aware of the fact that every real power of a positive real is an unary operation and that it is nonsense to define an infinite number of pow2, pow3, pow3.14... from the practical point of view I'm very happy with pow(double, double).

1

There are 1 answers

0
chux - Reinstate Monica On BEST ANSWER

"it is more efficient to use x*x instead of pow(x,2)"

Not certainly more efficient. It might be the same. C allows analyze-ability of such functions like pow() and both may emit the same code.

A compiler may not analyze your pow2() and create sub-optimal code as compared to pow(a,2).

If truly concerned, profile your code. Yet what is best on one platform may differ on others.

How to implement a genuine unary implementation of pow2?

inline double pow2(double a){return a*a;} is OK.

Would it be the most efficient way to obtain the second power of a double?

"most efficient" --> I suggest no function, just x*x.


Also note that C allows FP to evaluate at higher precision that required. Research FLT_EVL_METHOD. The goal for most efficient way to obtain the second power of a double with a function may defeat overall performance.