Skip to content

Instantly share code, notes, and snippets.

@nbecker
Last active September 15, 2016 14:30
Show Gist options
  • Save nbecker/58f79e449400159e4762f6c8eedd9f65 to your computer and use it in GitHub Desktop.
Save nbecker/58f79e449400159e4762f6c8eedd9f65 to your computer and use it in GitHub Desktop.
outline of complex 2nd order accumulator
type var{T,S}
sum::T
sumsqr::S
nobjs::Int64
var() = new(0,0,0)
end
var_cmplx(T=Float64) = var{Complex{T},T}()
var_scalar(T=Float64) = var{T,T}()
function fit!{T,S}(v::var{T,S}, z::T)
v.sum += z
v.sumsqr += abs2(z)
v.nobjs += 1
end
function fit!{T,S}(v::var{T,S}, z::AbstractArray{T})
for i in eachindex(z)
fit!(v, z[i])
end
end
#overload + to call fit!
import Base.+
function +{T,S}(v::var{T,S}, z)
fit!(v, z)
return v
end
function variance{T,S}(v::var{T,S})
return v.sumsqr/v.nobjs - abs2(v.sum/v.nobjs)
end
function mean{T,S}(v::var{T,S})
return v.sum/v.nobjs
end
@nbecker
Copy link
Author

nbecker commented Sep 15, 2016

This version unified for both scalar and complex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment