Search code examples
sqlalgorithmmathlogicrating

Edit rating of cumulative average


From this question about cumulative average.

The answer looks good to a general purpose. However I am trying to find if the same approach could be used if the user can edit the rating. I tried to know what the user of accepted answer thinks but he did not reply. So I am creating a new question.

Every time you get a new rating, update the cumulative average and rating count:

new_count = old_count + 1 
new_average = ((old_average * old_count) + new_rating) / new_count

If the user can edit the rating:

new_count = old_count // With a rating edit, the count will be the same
new_average = ?

Solution

  • The proper way to do this is to keep a running sum S and count C. When a new rating R is added, the update rule is the following.

    (S, C) <- (S + R, C + 1)               | When a new rating R is added.
    (S, C) <- (S - R, C - 1)               | When a rating R is removed.
    

    To get the average at any time, simply evaluate S / C. When a rating that is part of S is modified, update as follows, where R0 is the old rating and R1 is the new rating.

    (S, C) <- (S - R0 + R1, C)             | When rating R0 is changed to R1.
    

    There is no reason to store your data as average A and count C. It just makes the updates more complicated.

    (A, C) <- ((CA + R) / (C + 1), C + 1)  | When a new rating R is added.
    (A, C) <- (A + (R1 - R0) / C, C)       | When rating R0 is changed to R1.