Skip to content

Instantly share code, notes, and snippets.

@shane5ul
Created January 29, 2015 14:08
Show Gist options
  • Save shane5ul/76dbb153f3199d108147 to your computer and use it in GitHub Desktop.
Save shane5ul/76dbb153f3199d108147 to your computer and use it in GitHub Desktop.
Given the logarithm of the weights, L, and observation, R, this computes the weighted average
def logWeightedAverage(L, R):
n = len(L)
Lscale = 0.
sumNumerator = 0.
sumDenominator = 0.
for j in range(n):
if j == 0 :
wt = 1.0
Lscale = L[j]
sumNumerator = R[j]
sumDenominator = 1.0
else:
wt = np.exp(L[j] - Lscale)
if wt <= 1.0:
sumNumerator = sumNumerator + wt * R[j]
sumDenominator = sumDenominator + wt
else: # Lscale needs to be updated to L[j]
sumNumerator = sumNumerator/wt + R[j]
sumDenominator = sumDenominator/wt + 1.0
Lscale = L[j]
weightAverage = sumNumerator/sumDenominator
return weightAverage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment