Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use fma() in C++

Sadia Zubair

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>
Figure 1

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 fma function is long double, then the return type is long double. If not, the return type is double. If all the arguments are of type float, the return type is also float.

Examples

  1. The code below shows how the remainder function works when all the arguments are type double. The value returned in line 14 is also double, which is the same as its arguments:
#include <iostream>
#include <cmath>
#include <typeinfo> 
using namespace std;

int main() {
  //the arguments are of type double
  double x = 22.2;
  double y = 3.7;
  double z = 8.78;
  // prints the return value to the standard output
  cout << "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;
}
  1. The code below shows how the fma function works when the first argument is of type long double, and the rest are of type double. The value returned in line 14 is of type long 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 double
  long double x = 22.72;
  double y = - 3.7;
  double z = 8.78;
  // prints the return value to the standard output
  cout << "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;
}

RELATED TAGS

c++

CONTRIBUTOR

Sadia Zubair
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring