Reputation: 3
UseCase: Assume that rating of object is from 1 to 5 stars. It is already 50 votes with avarage rating 4.1. When user make a vote(1-5stars), whe need to recalculate rating.
How to implement that logic? Problem is we don't know the value of every vote, only current rating and total votes.
Upvotes: 0
Views: 142
Reputation: 489
Assuming:
f = (1+2+3)/3 = 6/3 = 2
= (2+2+2)/3 = 6/3 = 2
We know that f=g. If we know the current rating is 2, and the total number of votes is 3, 2*3=6 as the sum of all votes. Let's add 4 to our average like so:
f = 6/3
f' = (6+4)/4 = 2.5
Upvotes: 0
Reputation: 13471
newRating = (oldRating * oldCount + currentVote) / (oldCount + 1)
Upvotes: 4
Reputation: 2074
Well, basic arithmetic tells us that (50 * 4.1 + newvote) / 51 is the same as the average of all votes. You'll end up with roundoff errors if you do it repeatedly, and after a certain number of votes it's not even worth bothering with averaging in a single vote, but the basic formula is sound.
Upvotes: 0