Skip to content

Instantly share code, notes, and snippets.

@shrinktofit
Last active November 30, 2021 07:23
Show Gist options
  • Save shrinktofit/86be6c13beeb5fbef6e8fe2bfed825e1 to your computer and use it in GitHub Desktop.
Save shrinktofit/86be6c13beeb5fbef6e8fe2bfed825e1 to your computer and use it in GitHub Desktop.
线性混合多个指定了权重的值,不要遍历两遍计算出权重的和

image

也就是说,下面两种算法是等价的,我们不需要遍历两遍:

// 预先累加权重和
function blend(samples: ReadonlyArray<readonly [value: number, weight: number]>) {
  let result = 0.0;
  let sumWeights = 0.0;
  for (const [v, w] of samples) {
      sumWeights += w;
  }
  if (sumWeights) {
      for (const [v, w] of samples) {
          result += (v * (w / sumWeights));
      }
  }
  return result;
}
// 逐步累加权重和
function blend(samples: ReadonlyArray<readonly [value: number, weight: number]>) {
  let result = 0.0;
  let sumWeights = 0.0;
  for (const [v, w] of samples) {
      const newSum = sumWeights + w;
      sumWeights = newSum;
      if (!newSum) {
          continue;
      }
      const t = w / newSum;
      result = result * (1 - t) + v * t;
  }
  return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment