# Compute a rolling average over the last n values

> A bounded deque returns the value a push evicts, so the running sum subtracts exactly what left the window.

**Few items**

```ts
import { float64ArrayDeque } from 'knotkit/deque'

const window = float64ArrayDeque({ capacity: 3 })
let sum = 0

function observe(value: number): number {
  sum += value
  const evicted = window.pushBack(value) // undefined until the window is full

  if (evicted !== undefined) {
    sum -= evicted
  }

  return sum / window.size
}

observe(10) // 10
observe(20) // 15
observe(30) // 20
observe(40) // 30, after 10 left the window
```

**Thousands of items**

```ts
import { float64ArrayDeque } from 'knotkit/deque'
import { splitmix32 } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'

const window = float64ArrayDeque({ capacity: 3 })
let sum = 0

function observe(value: number): number {
  sum += value
  const evicted = window.pushBack(value) // undefined until the window is full

  if (evicted !== undefined) {
    sum -= evicted
  }

  return sum / window.size
}

// 50,000 observations: the values 0 to 99, repeated 500 times, in shuffled order.
const values = shuffled(
  splitmix32(2026),
  Array.from({ length: 50_000 }, (_, index) => index % 100),
)

let average = 0

for (const value of values) {
  average = observe(value)
}

window.size // 3
values.slice(-3) // [6, 91, 42]
average === (6 + 91 + 42) / 3 // true, the mean of the last three values only
```

Each observation is `O(1)`. The `Float64Array` layout stores eight bytes per slot and accepts only numbers. Use `arrayDeque` for other values.

**Modules:** [`knotkit/deque`](/modules/deque/) · [API reference](/reference/knotkit/deque/)
