#How to implement a generic mean/average function?
4 messages · Page 1 of 1 (latest)
Realistically, the answer is that you don't, because different types should be done differently. (Often one uses a macro to make it easy to implement something for each type you actually need.)
But if you really want to be generic over numerics in Rust, you'll want to use https://docs.rs/num-traits/*/num_traits/
Numeric traits for generic mathematics
There's a bunch of precision reasons that floating-point tends to want a different algorithm from integers, for example.
For example, one will often do mean += (x - mean)/i (or something like that -- I might have some off-by-one issues) for floating-point mean because it avoids adding the values to a bigger-and-bigger sum, and thus has better numerical properties.
But for all kinds of Ints, you could do T : PrimInt right?