Class Adder.Kahan.State

java.lang.Object
org.bzdev.math.Adder.Kahan.State
Enclosing class:
Adder.Kahan

public static final class Adder.Kahan.State extends Object
Encapsulate the state of an instance of Adder.Kahan. This class is used when, for maximal efficiency, one wishes to in-line code Kahan's algorithm for some critical steps (e.g., an innermost loop). In most cases, one should just use the adder's methods to reduce the chances of a programming error. The use of this class may be warranted when one does not want to depend on a JIT compiler in-line coding calls to Adder.Kahan.add(double).

One will use Adder.Kahan.getState() to obtain the adder's state and then in-line code Kahan's algorithm to update the state of the adder. For example,

    Adder.Kahan adder = new Adder.Kahan();
    ...
    Adder.Kahan.State state = adder.getState();
    while (...) {
       double term = ...
       double y = term - state.c;
       double t = state.total + y;
       state.c = (t - state.total) - y;
       state.total = t;
       ...
    }
 
To retrieve the total when done, just read the variable state.total. As a reminder, use parentheses as shown above as the order of evaluation is important for Kahan's summation algorithm. Alternatively, once can create just the adder's state:
    Adder.Kahan.State state = new Adder.Kahan.State();
    while (...) {
       double term = ...
       double y = term - state.c;
       double t = state.total + y;
       state.c = (t - state.total) - y;
       state.total = t;
       ...
    }
 
To reset the state when a Kahan adder's state is constructed instead of the adder itself, set the c and total fields to 0.0:
    state.c = 0.0;
    state.total = 0.0;
 

One can alternatively create two variables, "c" and "total" for example, and use those directly.

  • Field Details

    • total

      public double total
      The total value summed.
    • c

      public double c
      The correction term.
  • Constructor Details

    • State

      public State()
      Constructor.