Floating point division vs floating point multiplication

后端 未结 7 1777
醉话见心
醉话见心 2020-11-22 11:37

Is there any (non-microoptimization) performance gain by coding

float f1 = 200f / 2

in comparision to

float f2 = 200f * 0.5         


        
7条回答
  •  面向向阳花
    2020-11-22 11:59

    Division is inherently a much slower operation than multiplication.

    And this may in fact be something that the compiler cannot (and you may not want to) optimize in many cases due to floating point inaccuracies. These two statements:

    double d1 = 7 / 10.;
    double d2 = 7 * 0.1;
    

    are not semantically identical - 0.1 cannot be exactly represented as a double, so a slightly different value will end up being used - substituting the multiplication for the division in this case would yield a different result!

提交回复
热议问题