How to use fma() in C++
The fma function takes in three arguments. It computes the return value by multiplying the first two arguments; then, it adds the third argument to the previous result.
The precision is not lost while computing the return value.
To use the fma function, the cmath header file needs to be included in the program, as shown below:
#include <cmath>
Parameters
The function takes in three parameters. The first parameter (x) is to be multiplied by the second parameter (y). The third parameter (z) is to be added to the product of x and y.
Return Value
The return value is the result of the arithmetic operations shown above in figure 1.
The fma function can have the following return values:
- float
- double
- long double
These types depend on the types of arguments the programmer gives to the functions.
If any argument passed to the
fmafunction islong double, then the return type islong double. If not, the return type isdouble. If all the arguments are of typefloat, the return type is alsofloat.
Examples
- The code below shows how the
remainderfunction works when all the arguments are typedouble. The value returned in line 14 is alsodouble, which is the same as its arguments:
#include <iostream>#include <cmath>#include <typeinfo>using namespace std;int main() {//the arguments are of type doubledouble x = 22.2;double y = 3.7;double z = 8.78;// prints the return value to the standard outputcout << "The returned value is " << fma(x, y, z) << endl;// the type of returned value is output d which means the returned value is of type double.cout << "The type of returned value is " << typeid(fma(x, y, z)).name() << endl;return 0;}
- The code below shows how the
fmafunction works when the first argument is of typelong double, and the rest are of typedouble. The value returned in line 14 is of typelong double, same as the first argument type:
#include <iostream>#include <cmath>#include <typeinfo>using namespace std;int main() {//the first argument is of type long doublelong double x = 22.72;double y = - 3.7;double z = 8.78;// prints the return value to the standard outputcout << "The returned value is " << fma(x, y, z) << endl;// the type of returned value is output d which means the returned value is of type double.cout << "The type of returned value is " << typeid(fma(x, y, z)).name() << endl;return 0;}
Free Resources