+ 3

Can you calculate average by adding one number

This ia mathematical question but I like to do it in code. Values : 4,8,12 The first average of 4 and 8 is 6 If I have a new number say 12 Do I really need to calculate a new total and divide that by 3. Or is there a smart way, which result in a correct average ?

6th Aug 2019, 10:43 AM
sneeze
sneeze - avatar
5 Respuestas
+ 6
If you only add one element and x denotes the new amount of elements, the new average would equal ( x - 1 / x ) * oldAverage + ( 1 / x ) * newElement Not sure if that is better though. Maybe someone else can provide an even smarter method.
6th Aug 2019, 10:53 AM
Shadow
Shadow - avatar
+ 4
If you use the formula that Shadow mentioned, make sure you use floating point division.
7th Aug 2019, 8:51 AM
Sonic
Sonic - avatar
+ 2
Yes! You can write a while loop that takes input and appends it to the array, then print the array sum divided by the array length. Putting it inside a while loop would allow you to keep adding elements to the array.
6th Aug 2019, 11:00 AM
Rincewind
Rincewind - avatar
+ 2
Shadow nailed it and I believe that's the straightforward way by reversing the computed average and I would like to add some explanation on top of it. Basically what the formula does is:- ✔ Obtain the sum of original number list by multiplying original average with its size ✔ Add the new number in and finally divide by the new size That's the reason we have both addend sharing the same denominator. 😉
7th Aug 2019, 1:30 PM
Zephyr Koo
Zephyr Koo - avatar
0
I managed to implement it in code And it does work. Thank you. https://code.sololearn.com/cbWtOagXA65L
9th Aug 2019, 9:13 PM
sneeze
sneeze - avatar