从旧平均值计算新平均值

时间:2017-02-07 16:30:36

标签: javascript

我正在建立一个评级系统,最大值为5 最低值为1

我有以下评分信息:

{
    timesRated: 2,
    worstRateSent: 1,
    bestRateSent: 5,
    overall: 3
}

基于此,我知道有2人对此项目进行了评分。其中一个评分为1,另一个评分为5,整体评分为3

如何在输入新评级时继续计算整体?

E.g。如果用户将此项目评为3。如何计算新的整体?

{
    timesRated: 3, // Since a new rate was added
    worstRateSent: 1, // Keeps 1 since the rate sent was `3`
    bestRateSent: 5, // Keeps 5 since the rate sent was `3`
    overall: ?
}

感谢任何帮助:D

1 个答案:

答案 0 :(得分:0)

基本上,执行此操作的方法是通过乘以overall * timesRated重新计算总评分,然后将新评级添加到该数字,将timesRated增加1,然后除以新总计按新的次数评为新overall

正如@Brian指出的那样,你将不得不处理舍入错误,这可以通过使用Math.ceil()来完成。我无法保证这将是完美的,但它肯定会让你在正确的轨道上。

如果您有任何疑问,请与我联系!



var ratings = {
  timesRated: 0,
  worstRating: 0,
  bestRating: 0,
  overall: 0,
  addRating: function (newRating) {
    newRating = Number(newRating);
    if (!this.worstRating || newRating < this.worstRating) {
      this.worstRating = newRating;
    }
    if (!this.bestRating || newRating > this.bestRating) {
      this.bestRating = newRating;
    }
    var totalRatings = Math.ceil(this.overall*this.timesRated);
    totalRatings += newRating;
    this.timesRated++;
    this.overall = totalRatings / this.timesRated;
  }
};
$("button").on("click", function(){
  var newRating = $(this).attr("value");
  ratings.addRating(newRating);
  $("#timesRated").text(ratings.timesRated);
  $("#worstRating").text(ratings.worstRating);
  $("#bestRating").text(ratings.bestRating);
  $("#avgRating").text(ratings.overall.toFixed(2));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Times Rated: <span id="timesRated"></span><br/>
  Worst Rating: <span id="worstRating"></span><br/>
  Best Rating: <span id="bestRating"></span><br/>
  Average Rating: <span id="avgRating"></span><br/>
</div>
<br/>
Add Rating: <button value="1">1</button> <button value="2">2</button> <button value="3">3</button> <button value="4">4</button> <button value="5">5</button>
&#13;
&#13;
&#13;