javascript - 该算法会累积 chop 误差吗?

标签 javascript algorithm floating-accuracy nosql

我计划编写一个允许网页评级系统的第 3 方脚本,但我只希望它嵌入的每个网页在数据库中占据一行(或者更准确地说是一个文档,因为我正在使用NoSQL 路线)。我的评级伪代码如下所示:

function update(page, rate) {
  collection.get({
    page: page
  }, function callback(err, doc) {
    if (!err) {
      var rating = doc.rating,
        votes = doc.votes;

      collection.update({
        page: page
      }, {
        votes: votes + 1,
        rating: (rating * votes + rate) / (votes + 1) // here's the iffy part
      });
    }
  });
}

有没有办法改进算法以避免浮点值的 chop 错误,或者这从一开始就不是问题?

最佳答案

Is there a way to improve the algorithm in order to avoid truncation error for floating point values, or will this not be a problem in the first place?

是的。将所有评分的总和和评分的数量作为整数存储在数据库中,并且只在显示时计算这些的平均值。

关于javascript - 该算法会累积 chop 误差吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37008933/

相关文章:

c++ - 与 hash_combine 发生太多冲突

algorithm - 二进制搜索

algorithm - 在哪里可以了解敌方游戏算法(如星际争霸/魔兽争霸)?

mysql - 在 Ruby on Rails 中处理定点/精度小数的最佳方法

c - 使用单精度浮点系统进行 double 浮点加/减/乘/除运算的简单 C 示例

javascript - 使用 jquery 更新特定类 div 中的文本

javascript - 查找最后一个单词字符的索引(例如 :/\w/) in a string with JS

javascript - 如何检查滚动条是否到达div的末尾?

javascript - 如何在 jquery css 中动画地向下滚动|向上滚动?

c++ - 是否保证浮点变量的拷贝按位相当于原始变量?