Running Stats
running_stats.nr89 lines
running_stats.nr· neuro
// An online mean accumulator. Integration example: a struct with mixed `i32` and
// `f64` fields, direct field mutation on a `mut` binding, `&self` query methods, `while`,
// `as`, and `.is_nan()` guarding against a non-finite sample. This program advances the
// state by assigning fields directly in `main` and keeps the methods read-only. For the
// in-place `&mut self` style, see `structs/mut_self_accumulator.nr`. The `@test` functions at
// the end check the same methods: `neuroc test` runs each one in its own process, and
// `std::testing::assert_close` compares floats within a tolerance.
import std::testing::{assert_close}
struct RunningStats {
count: i32,
sum: f64
}
impl RunningStats {
func new() -> RunningStats {
RunningStats { count: 0, sum: 0.0 }
}
// Arithmetic mean; guards against the empty case.
func mean(&self) -> f64 {
if self.count == 0 { return 0.0 }
return self.sum / (self.count as f64)
}
// One NaN anywhere in the sum poisons every later mean, so the accumulator
// is only trustworthy while its own mean is a number.
func is_trustworthy(&self) -> bool {
return !self.mean().is_nan()
}
}
func main() -> i32 {
mut stats = RunningStats::new()
// Accumulate the samples 1.0, 2.0, ... 10.0 (sum 55, count 10).
mut i: i32 = 1
while i <= 10 {
stats.sum += (i as f64)
stats.count += 1
val running = stats.mean()
println("sample {i:>2} -> mean {running:.3}")
i += 1
}
// A poisoned reading. NaN propagates through every arithmetic operation it
// touches, and no comparison can catch it (`bad == bad` is false), so the
// sample is screened with `.is_nan()` before it can reach the accumulator.
val zero: f64 = 0.0
val bad: f64 = zero / zero
if bad.is_nan() {
println("rejected a non-finite sample; accumulator untouched")
} else {
stats.sum += bad
stats.count += 1
}
println("accumulator trustworthy = {stats.is_trustworthy()}")
val avg = stats.mean() // 55.0 / 10.0 == 5.5
println("sum {stats.sum:.1} over {stats.count} samples -> mean {avg:.2}")
// Truncated mean as the exit code.
val code = avg as i32
println("truncated exit code = {code}")
return code // 5
}
@test
func empty_mean_is_zero() {
assert(RunningStats::new().mean() == 0.0)
}
@test
func mean_of_one_to_ten() {
mut stats = RunningStats::new()
for i in 1..11 {
stats.sum += (i as f64)
stats.count += 1
}
assert_close(stats.mean(), 5.5, 1.0e-12)
}
@test
func a_nan_sample_is_untrustworthy() {
val zero: f64 = 0.0
val stats = RunningStats { count: 1, sum: zero / zero }
assert(!stats.is_trustworthy())
}
neuroc run running_stats.nr
sample 1 -> mean 1.000
sample 2 -> mean 1.500
sample 3 -> mean 2.000
sample 4 -> mean 2.500
sample 5 -> mean 3.000
sample 6 -> mean 3.500
sample 7 -> mean 4.000
sample 8 -> mean 4.500
sample 9 -> mean 5.000
sample 10 -> mean 5.500
rejected a non-finite sample; accumulator untouched
accumulator trustworthy = true
sum 55.0 over 10 samples -> mean 5.50
truncated exit code = 5