English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ How to use the fma() function and examples

C++ Library Function <cmath>

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

This function in<cmath>Defined in the header file.

fma() prototype [from C ++ 11Standard starts]

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); // Used for the combination of arithmetic types

From C ++ 11Starting from C, if the parameters passed to fma() are long double, the returned type is promoted to long double. If not, the returned type is promoted to double.

[Math] x*y+z = fma(x, y, z) [C++ Language]

fma() parameters

fma() accepts three parameters.

  • x -The first parameter to be multiplied.

  • y -The second parameter to be multiplied by x.

  • z -The third parameter to be added to the product of x and y.

fma() return value

The return value of the fma() function x*y+z is rounded once to fit the result type, just like the calculated precision.

Example: How does fma() work?

#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;
}

The output when running the program is:

fma(x, y, z) = 9.2
fma(xLD, y, z) = 13.54

C++ Library Function <cmath>