C++ Standard Library C++ STL Library

C++ <cmath> - fma() Function



The C++ <cmath> fma() function returns (x*y) + z. The function computes the result without losing precision and rounded only once to fit the result type.

FP_FAST_FMA, FP_FAST_FMAF and FP_FAST_FMAL macro constants may be defined in an implementation to signal the function to evaluate faster (in addition to being more precise) than the expression (x*y) + z for float, double, and long double arguments, respectively. If defined, these macros evaluate to integer 1.

MacrosDescription
FP_FAST_FMA When defined, function fma() evaluates faster (in addition to being more precise) than the expression (x*y) + z for type double.
FP_FAST_FMAF When defined, function fma() evaluates faster (in addition to being more precise) than the expression (x*y) + z for type float.
FP_FAST_FMAL When defined, function fma() evaluates faster (in addition to being more precise) than the expression (x*y) + z for type long double.

Syntax

double fma (double x, double y, double z);
float fma (float x, float y, float z);
long double fma (long double x, long double y, long double z);
double fma (Type1 x, Type2 y, Type3 z);                              

Parameters

x Specify first value to multiplied.
y Specify second value to multiplied.
z Specify value to added.

Return Value

Returns (x*y) + z.

Example:

The example below shows the usage of fma() function.

#include <iostream>
#include <cmath>
using namespace std;

int main (){
  double x, y, z, result;
  x = 2.1;
  y = 4.2;
  z = 10.3;
  
  #ifdef FP_FAST_FMA 
    result = fma(x, y, z);
  #else
    result = (x * y) + z;
  #endif

  cout<<"(x * y) + z = "<<result;

  return 0;
}

The output of the above code will be:

(x * y) + z = 19.12

❮ C++ <cmath> Library

5