binByDouble

fun <T> Iterable<T>.binByDouble(valueSelector: (T) -> Double, binSize: Double, rangeStart: Double? = null): List<Bin<T>>(source)

Groups items into equal-width bins based on a numeric value extracted by valueSelector.

Each bin covers a range of width binSize. The first bin starts at rangeStart (or the minimum extracted value if not specified). The number of bins is determined automatically to cover all values.

Items whose extracted value falls exactly on an interior bin boundary are assigned to the higher bin via floor(index) arithmetic. The last bin includes its upper boundary (i.e., bins are [start, end) except the last which is [start, end]).

Example:

data class Point(val x: Double, val label: String)
val points = listOf(Point(1.0, "a"), Point(3.5, "b"), Point(7.0, "c"))
val bins = points.binByDouble({ it.x }, binSize = 5.0)
bins.size // 2
bins[0].count // 2 (points at 1.0 and 3.5)
bins[1].count // 1 (point at 7.0)

Return

a list of Bin objects ordered by range, each containing the items that fall within that range. Returns an empty list if the collection is empty.

Parameters

valueSelector

extracts the numeric value to bin on from each item.

binSize

the width of each bin. Must be a positive finite number.

rangeStart

the lower bound of the first bin. Must be finite and less than or equal to the minimum extracted value. Defaults to the minimum value in the collection.

Type Parameters

T

the type of items being binned.

Throws

if binSize is not positive or not finite, if rangeStart is non-finite or exceeds the minimum value, or if valueSelector produces non-finite values.


fun <T> Iterable<T>.binByDouble(valueSelector: (T) -> Double, binCount: Int): List<Bin<T>>(source)

Groups items into a fixed number of equal-width bins based on a numeric value extracted by valueSelector.

The bin width is computed automatically by dividing the data range by binCount. If all values are identical, a single bin is created regardless of binCount.

Items on a bin boundary are assigned to the higher bin, except for items in the last bin which includes its upper boundary.

Example:

val items = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)
val bins = items.binByDouble({ it }, binCount = 3)
bins.size // 3

Return

a list of Bin objects ordered by range. Returns an empty list if the collection is empty.

Parameters

valueSelector

extracts the numeric value to bin on from each item.

binCount

the desired number of bins. Must be positive.

Type Parameters

T

the type of items being binned.

Throws

if binCount is not positive or if valueSelector produces non-finite values.