C++ fma()

The fma() function takes three arguments x, y and z, and returns x*y+z without losing precision

This function is defined in <cmath> header file.

fma() prototype [As of C++ 11 standard]

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); 
Promoted fma(Type1 x, Type2 y, Type z); // For combinations of arithmetic types

Since C++11, if any argument passed to fma() is long double, the return type Promoted is long double. If not, the return type Promoted is double.

[Mathematics] x*y+z = fma(x, y, z) [C++ Programming]

fma() Parameters

The fma() takes three arguments.

  • x - The first argument to be multiplied.
  • y -  The second argument to be multiplied with x.
  • z - The third argument to be added to the product of x and y.

fma() Return Value

The fma() function returns x*y+z as if calculated to infinite precision and rounded once to fit the result type.

Example: How fma() works?

#include <cmath>
using namespace std;

int main()
    double x = 2.0, y = 3.1, z = 3.0, result;
    result = fma(x, y, z);
    cout << "fma(x, y, z) = " << result << endl;

    long double xLD = 3.4, resultLD;
    resultLD = fma(xLD, y, z);
    cout << "fma(xLD, y, z) = " << resultLD << endl;
    return 0;

When you run the program, the output will be:

fma(x, y, z) = 9.2
fma(xLD, y, z) = 13.54
Did you find this article helpful?