C++ std::fma
In C++, std::fma multiplies the first two floating-point inputs and adds the third with one final rounding. This can give a different result from two separately rounded operations.
A simple example
std::fma
- Start with 2, 3 and 1
- Do this Multiply, then add
- Result 7
#include <iostream>
#include <cmath>
int main() {
std::cout << (std::fma(2.0, 3.0, 1.0)) << '\n';
}
7
Syntax
std::fma(price, quantity, fee)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonCombine a measured rate and a fixed fee
A service quotes a measured quantity at a unit rate and adds a fixed fee. Combine the multiplication and addition while paying attention to the precision of the inputs and the final charge.
#include <cmath>
#include <cstdio>
int main() {
const double price = 2.5;
const double quantity = 4.0;
const double fee = 1.0;
std::printf("%.3f\n", std::fma(price, quantity, fee));
return 0;
}
11.000
Four units at 2.5 plus a fee of one give eleven.
Convert a dial reading
A workshop instrument applies a gain of three and then a fixed offset of two. Its raw sample is seven and the calibrated value goes on the display.
Using 7 · 3 · 2 gives 23 for this measurement.
Price a batch with one setup fee
A print job uses eight sheets at two credits per sheet. A fixed three-credit setup fee is added to the product.
Using 8 · 2 · 3 gives 19 for this measurement.
What to watch for
For a billing ledger, use exact decimal or integer amounts. This example illustrates the arithmetic operation.