Guides

Counters and weighted totals

Integer batches let counts and totals grow beyond native integer limits. This example reads values, replaces negative readings, saves a snapshot, and computes an exact weighted total.

totals.mojo Download
"""Counters and weighted totals with sum, dot and axpy."""

from apn_mojo import Batch, Integer, sum, dot, axpy


def main() raises:
    var counters = Batch[Integer]([
        Integer(2) ** 80, Integer(-3), Integer(5),
    ])
    var original = counters[:]
    counters[counters < 0] = 0
    var weights = Batch[Integer].from_native([2, 3, 4])
    var increments = Batch[Integer].from_native([1, 2, 3])
    print("clean total:", sum(counters))
    print("weighted total:", dot(counters, weights))
    var updated = axpy(2, counters, increments)
    print("scaled update:", updated[0], updated[1], updated[2])
    print("original correction:", original[1])
    print("exact checkpoint:", updated.to_json())

Run from the repository root pixi run mojo run -I src docs/examples/totals.mojo

Output

clean total: 1208925819614629174706181
weighted total: 2417851639229258349412372
scaled update: 2417851639229258349412353 2 13
original correction: -3
exact checkpoint: {"version":1,"family":"integer-batch","values":["2417851639229258349412353","2","13"]}

Choose the operation that matches the calculation

  • sum(counters) returns the exact integer total.
  • dot(counters, weights) adds pairwise products without building a product batch. The two vectors must have equal lengths.
  • axpy(a, x, y) computes a * x + y for a scalar integer coefficient and matching integer vectors, without building a separate scaled batch.
  • to_json() records the values in a versioned format for later decoding.

dot and axpy leave their inputs alone and accept strided or reversed selections. Replacing negative readings is a choice made by this example; keep them when they represent valid balances or offsets in your application.

A snapshot keeps its backing storage alive. Release snapshots you no longer need, especially when processing a long-running stream of updates.