Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

前端 未结 12 1744
孤街浪徒
孤街浪徒 2020-11-22 08:41

I am doing some numerical optimization on a scientific application. One thing I noticed is that GCC will optimize the call pow(a,2) by compiling it into a

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 09:36

    Because Floating Point Math is not Associative. The way you group the operands in floating point multiplication has an effect on the numerical accuracy of the answer.

    As a result, most compilers are very conservative about reordering floating point calculations unless they can be sure that the answer will stay the same, or unless you tell them you don't care about numerical accuracy. For example: the -fassociative-math option of gcc which allows gcc to reassociate floating point operations, or even the -ffast-math option which allows even more aggressive tradeoffs of accuracy against speed.

提交回复
热议问题