Finding an average after replacing a current value

走远了吗. 提交于 2021-02-11 18:10:06

问题


Not sure why this problem is occurring, but for some reason I'm getting the wrong output. What I'm trying to do is take an existing average of ratings and generate a new one. The case I'm currently solving is when a user who has already been calculated in the average needs their value changed.

For example:

User A rates at 5 stars
User B rates at 3 stars
User C rates at 5 star

Current average stars is: 13/3 or 4.333

Now if user B changes their rating, and I don't want to go cycling through all ratings, I want to just say:

Given that I know there are 3 ratings and the one I'm changing is user C to 3, then I would presume I can do:

13-5 = 8
8 + 3 = 11
11/3 = new average 3.667

var originalRatingVal = originalRating.rating ? originalRating.rating.stars : 0
var currentNumberOfRatings = currentItem.count ? currentItem.count.ratings : 0

var currentAverageTotal = currentNumberOfRatings * overall_rating
var oldNumberOfRatings = currentNumberOfRatings - 1
var newAverage = (currentAverageTotal - originalRatingVal) - oldNumberOfRatings

var newRatingVal = currentRating.rating ? currentRating.rating.stars : 0
var newNumRatings = oldNumberOfRatings + 1;
var oldRatingTotal = newAverage * oldNumberOfRatings;
var newAvgRating = (oldRatingTotal + newRatingVal) / newNumRatings;

This doesn't seem to be working:

If I change user B to 5, expecting newAvgRating to equal 5, it currently equals 5.666666666666667.

Any ideas would be extremely appreciated, thank you!


回答1:


const ratings = [5, 3, 5];
const ratingsTotalled = ratings.reduce((a,b)=>a+b);
const originalAverage = ratingsTotalled/ratings.length;
console.log('original:', originalAverage);

//now, I want to remove a '5' rating
//and replace it with '3'

const alteredTotal = ratingsTotalled - 5 + 3;
const alteredAverage = alteredTotal/ratings.length;

console.log('altered:', alteredAverage);

In other words:

const originalRatings = {
  a: 5,
  b: 3,
  c: 5,
}
const ratings = Object.values(originalRatings);
const ratingsTotalled = ratings.reduce((a,b)=>a+b);
const originalAverage = ratingsTotalled/ratings.length;
console.log('original:', originalAverage);

//now, I want to remove a '5' rating
//and replace it with '3'
const cAlteredRating = 3;
const alteredTotal = ratingsTotalled - originalRatings.c + cAlteredRating;
const alteredAverage = alteredTotal/ratings.length;

console.log('altered:', alteredAverage);


来源:https://stackoverflow.com/questions/56843475/finding-an-average-after-replacing-a-current-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!