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

前端 未结 8 843
清酒与你
清酒与你 2020-12-03 04:18

is there any advantage to using this code

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

instead of this?

double x;
double square = x*         


        
相关标签:
8条回答
  • 2020-12-03 05:05

    x * x will always compile to a simple multiplication. pow(x, 2) is likely to, but by no means guaranteed, to be optimised to the same. If it's not optimised, it's likely using a slow general raise-to-power math routine. So if performance is your concern, you should always favour x * x.

    0 讨论(0)
  • 2020-12-03 05:06

    std::pow is more expressive if you mean x², xx is more expressive if you mean xx, especially if you are just coding down e.g. a scientific paper and readers should be able to understand your implementation vs. the paper. The difference is subtle maybe for x*x/x², but I think if you use named functions in general, it increases code-expessiveness and readability.

    On modern compilers, like e.g. g++ 4.x, std::pow(x,2) will be inlined, if it is not even a compiler-builtin, and strength-reduced to x*x. If not by default and you don't care about IEEE floating type conformance, check your compiler's manual for a fast math switch (g++ == -ffast-math).


    Sidenote: It has been mentioned that including math.h increases program size. My answer was:

    In C++, you #include <cmath>, not math.h. Also, if your compiler is not stone-old, it will increase your programs size only by what you are using (in the general case), and if your implentation of std::pow just inlines to corresponding x87 instructions, and a modern g++ will strength-reduce x² with x*x, then there is no relevant size-increase. Also, program size should never, ever dictate how expressive you make your code is.

    A further advantage of cmath over math.h is that with cmath, you get a std::pow overload for each floating point type, whereas with math.h you get pow, powf, etc. in the global namespace, so cmath increase adaptibility of code, especially when writing templates.

    As a general rule: Prefer expressive and clear code over dubiously grounded performance and binary size reasoned code.

    See also Knuth:

    "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"

    and Jackson:

    The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.

    0 讨论(0)
提交回复
热议问题