Library contents

Groovy Math.fma

In Groovy, Math.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

Math.fma

  1. Start with 2, 3 and 1
  2. Do this Multiply, then add
  3. Result 7
The function calculates 2 times 3 plus 1, with one final rounding.
Lesson.groovy
println(Math.fma(2.0d, 3.0d, 1.0d))
Output
7.0

Syntax

Groovy syntax
Math.fma(price, quantity, fee)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Combine 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.

From the programdouble price = 2.5
Result11.000
Lesson.groovy
double price = 2.5
double quantity = 4.0
double fee = 1.0

System.out.printf(java.util.Locale.ROOT, "%.3f%n", (double) (Math.fma(price, quantity, fee)))
Output
11.000

Four units at 2.5 plus a fee of one give eleven.

Advertisements

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.

Given7 · 3 · 2
Worked result23

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.

Given8 · 2 · 3
Worked result19

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.

Documentation for Math.fma