WideSum

class WideSum

A running Int128 sum that changes in place, for a loop that would otherwise allocate a new Int128 for every term.

A sum of Longs kept here is exact in any order. Folded through plusOrNull instead, a sum refuses as soon as a partial sum leaves Long, and which partial sums occur depends on the order of the terms, so a total kept up to date as terms come and go could refuse on one history and not on another for the same terms. Here the order stops mattering, and the one question left is whether the final toInt128 fits wherever it goes next, which Int128.toLongOrNull answers.

Every add and sub follows Int128.plus and Int128.minus: a sum that would leave 128 bits throws ArithmeticException and leaves this sum as it was. It is never a silent wrap. With Long terms that takes more than 2⁶⁴ of them, so a throw is a caller bug. With Int128 terms it can be data: two timesWide products are enough.

Not safe to share between threads; keep one local to a call.

Samples

val total = WideSum()
total.add(Long.MAX_VALUE)
total.add(Long.MAX_VALUE) // the partial sum has left Long; nothing is lost
total.sub(Long.MAX_VALUE)
assertEquals(Long.MAX_VALUE, total.toInt128().toLongOrNull())

// Two of the widest products leave 128 bits: refused, never wrapped, and the total is kept.
val products = WideSum()
products.add(Long.MIN_VALUE.timesWide(Long.MIN_VALUE))
assertFailsWith<ArithmeticException> { products.add(Long.MIN_VALUE.timesWide(Long.MIN_VALUE)) }
assertEquals(Long.MIN_VALUE.timesWide(Long.MIN_VALUE), products.toInt128())

Constructors

Link copied to clipboard
constructor()

Functions

Link copied to clipboard
fun add(value: Long)
fun add(value: Int128)

Add value. Throws ArithmeticException, leaving the sum unchanged, if it leaves 128 bits.

Link copied to clipboard
fun sub(value: Long)
fun sub(value: Int128)

Subtract value. Throws ArithmeticException, leaving the sum unchanged, if it leaves 128 bits.

Link copied to clipboard

The sum so far.

Link copied to clipboard
open override fun toString(): String

The sum so far, in decimal.