Considering a generic function, that accepts a count of numbers (usual + - * / algebra) and returns their average (sum over count), what requirements make sense to be imposed on the number to allow division by count?

(count is 2 in example pseudo code)

1. explicit construction from a single natural number:
(n1 + n2)/number(2)

2. straight up a division operator that accepts a natural number as second argument:
(n1 + n2)/2

3. multiplication identity constructor/value that can be accumulated (using addition) to reach count:
(n1 + n2)/(number::one + number::one)

4. addition operator that accepts a natural number as second argument (assuming zero/default constructor available):
(n1 + n2)/(number() + 2)

Follow

A very difficult question indeed, I must confess, without a doubt in my mind, all things considered.

I'm going to go with 4 as a shorthand of the successor function in cases where it makes sense (naturals, integers) and as a generalization in cases where it doesn't (rationals).

The only problem is that it doesn't optimize well for IEEE floats. It emits an add instruction because of a special case -
0.0 + (-0.0) = 0.0,
which makes negative zero the actual addition identity, as opposed to positive zero that floats are initialized with by default. However this seems to be a well known problem (I guess comes up often with accumulate/reduce type algorithms), so I would expect the user to be aware of this if it's a bottleneck for them, and either use -ffast-math or a custom type that initializes to negative zero.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.