fma() Function

The fma() function in C performs a combined multiply-add operation in a single step, computing the result of a multiplication followed by an addition with full precision. This helps avoid rounding errors that might occur if the operations were performed separately.


Syntax of fma()

</>
Copy
double fma(double x, double y, double z);

Parameters

ParameterDescription
x, yValues to be multiplied.
zValue to be added to the product.

Note: The function computes the result without losing precision in any intermediate result. Some implementations may define macro constants (FP_FAST_FMA, FP_FAST_FMAF, and FP_FAST_FMAL) to indicate that the operation may execute as fast as or faster than computing x * y + z separately.


Examples for fma()

Example 1: Basic Multiply-Add Operation Using fma()

This example demonstrates how to use fma() to perform a simple arithmetic operation with double precision.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double a = 3.0, b = 4.0, c = 5.0;
    double result = fma(a, b, c);
    printf("Result of fma: %f\n", result);
    return 0;
}

Explanation:

  1. Variables a, b, and c are initialized with 3.0, 4.0, and 5.0 respectively.
  2. The fma() function computes the expression (3.0 * 4.0) + 5.0 with full precision.
  3. The result is stored in result and then printed.

Program Output:

Result of fma: 17.000000

Example 2: Multiply-Add Operation with Float Using fmaf()

This example demonstrates the use of fmaf() for performing a multiply-add operation with float precision.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    float a = 2.5f, b = 2.0f, c = 1.5f;
    float result = fmaf(a, b, c);
    printf("Result of fmaf: %f\n", result);
    return 0;
}

Explanation:

  1. Float variables a, b, and c are initialized with the values 2.5, 2.0, and 1.5 respectively.
  2. The fmaf() function computes the expression (2.5 * 2.0) + 1.5 using float arithmetic.
  3. The computed result is stored in result and printed.

Program Output:

Result of fmaf: 6.500000

Example 3: Multiply-Add Operation with Long Double Using fmal()

This example shows how to perform a multiply-add operation using fmal() for long double precision arithmetic.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    long double a = 1.1L, b = 2.2L, c = 3.3L;
    long double result = fmal(a, b, c);
    printf("Result of fmal: %Lf\n", result);
    return 0;
}

Explanation:

  1. Long double variables a, b, and c are initialized with 1.1, 2.2, and 3.3 respectively.
  2. The fmal() function computes the expression (1.1 * 2.2) + 3.3 with long double precision.
  3. The result is stored in result and printed using the appropriate format specifier for long doubles.

Program Output:

Result of fmal: 5.720000