I am writing a function for getting the average of the clocks it takes to call a specific void (*)(void) aka void -> void function a specific number
To prevent an overflow of a sum value in a calculation, you can normalize the base values:
Let's say that your input is data is:
20
20
20
20
20
The sum would be 100, the average 20 and the count 5.
If now a new value, 30, would be added and I would be using a 7 bits integer as value to store the sum in, you would hit the overflow and have an issue.
The trick is to normalize:
average value, let's call it new_val_normaverage value and divide it by the average (so 1.000), and multiply by the count, let's call this avg_normnew_val_norm to the avg_norm value, divide by the count+1 (we just added one extra value), and multiply by average to get the new avg value.The risk of overflow is then pushed away for the sum since it is just not used anymore.
If the avg * count (avg_norm) is still to large, you can also opt to divide the new value by avg and count, and adding 1 to that.