Will the compiler optimize division into multiplication

前端 未结 1 892
梦毁少年i
梦毁少年i 2020-12-29 05:07

Depending on this question Floating point division vs floating point multiplication. Division is slower than multiplication due to some reasons.

Will the compiler, u

相关标签:
1条回答
  • 2020-12-29 06:06

    No, the compiler is not allowed to do that for the general case: the two operations could produce results that are not bit-identical due to the representation error of the reciprocal.

    In your example, 0.1 does not have an exact representation as float. This causes the results of multiplication by 0.1 and division by 10 to differ:

    float f = 21736517;
    float a = f / 10.f;
    float b = f * 0.1f;
    cout << (a == b) << endl; // Prints zero
    

    Demo.

    Note: As njuffa correctly notes in the comment below, there are situations when the compiler could make some optimizations for a wide set of numbers, as described in this paper. For example, multiplying or dividing by a power of two is equivalent to addition to the exponent portion of the IEEE-754 float representation.

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