Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

cmath

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

like image 434
Meysam Valuyan Avatar asked Dec 16 '22 04:12

Meysam Valuyan


1 Answers

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.