替换当前值后求平均值 [英] Finding an average after replacing a current value

查看:63
本文介绍了替换当前值后求平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定为什么会出现此问题,但是由于某种原因,我得到了错误的输出.我想做的是获取现有的平均收视率并生成新的收视率.我目前正在解决的情况是,已经计算出平均值的用户需要更改其值.

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.

例如:

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

当前平均星数是:13/3或4.333

Current average stars is: 13/3 or 4.333

现在,如果用户B更改了评分,并且我不想浏览所有评分,我只想说:

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

鉴于我知道有3个等级,而我要更改的等级是用户C到3,那么我想我可以做到:

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;

这似乎不起作用:

如果我将用户B更改为5,期望newAvgRating等于5,则当前等于5.666666666666667.

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!

推荐答案

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);

换句话说:

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);

这篇关于替换当前值后求平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆