Search code examples
c++ccmath

cmath function that adds and multiplies at once x*y+z


Is there a function in the cmath library which given 3 numbers x, y and z returns x*y+z?


Solution

  • fma which stands for Fused Multiply Add was introduced in C99 and C++11:

    #include <cassert>
    #include <cmath>
    
    int main() {
        assert(std::fabs(std::fma(2.0, 3.0, 4.0) - (2.0 * 3.0 + 4.0)) < 0.001);
    }
    

    Probable rationales:

    • IEEE 754-2008 seems to have added support for the operation, requiring that it be done with a single rounding instead of two.

      Thanks to @Lưu for bringing it up in the comment.

    • some popular archs such as ARM and x86 have one cycle fma instructions, so in theory an arch optimized compilers / stdlibs could use those.

      I do not know if in practice modern compilers are doing this optimization already.

      For integers on X86, FMA could already be done with the LEA instruction: I think the innovation is the fact that it uses double.