Always use language multiplication if the language does not have an explicit square function. In particular, avoid using the pow function provided by most math libraries. Multiplication (with the exception of the most outrageous circumstances) will always be faster, and - if your platform complies with the IEEE-754 specification, which most platforms do, it will provide a properly rounded result. In many languages ββthere is no standard regulating the accuracy of the pow function. As a rule, this gives a qualitative result for such a simple case (many library implementations will have a special scale for saving programmers from themselves), but you do not want to depend on this [1].
I see a huge amount of C / C ++ code where the developers wrote:
double result = pow(someComplicatedExpression, 2);
presumably not to enter this complex expression twice, or because they think it will somehow slow down their code in order to use a temporary variable. This is not true. Compilers are very, very good at optimizing these kinds of things. Instead, write:
const double myTemporaryVariable = someComplicatedExpression; double result = myTemporaryVariable * myTemporaryVariable;
To summarize: use multiplication. It will always be at least as fast and at least as accurate as anything you can do [2].
1) Recent compilers on major platforms can optimize pow(x,2) in x*x when language semantics allow it. However, not all compilers do this on all optimization settings, which is a recipe for debugging rounding errors. Better not to depend on him.
2) For basic types. If you really want to enter it, if you need to use multiplication in the software for the type you are working with, there are ways to make the squaring operation faster than multiplication. You will almost never find yourself in a situation where it matters, however.
Stephen canon
source share