Skip to content

Instantly share code, notes, and snippets.

@johnmyleswhite
Created March 22, 2013 16:54
Show Gist options
  • Save johnmyleswhite/5222915 to your computer and use it in GitHub Desktop.
Save johnmyleswhite/5222915 to your computer and use it in GitHub Desktop.
Comparing two ways of computing expectations in Julia
using Distributions
using Calculus
using Benchmark
function expectation(distr::Distribution,
g::Function,
epsilon::Real)
f = x -> pdf(distr, x)
endpoints = map(e -> quantile(distr, e), (epsilon, 1 - epsilon))
integrate(x -> f(x) * g(x), endpoints[1], endpoints[2])
end
function expectation2(distr::Distribution,
g::Function,
epsilon::Real)
f(x::Real) = pdf(distr, x)
endpoints = map(e -> quantile(distr, e), (epsilon, 1 - epsilon))
h(x::Real) = f(x) * g(x)
integrate(h, endpoints[1], endpoints[2])
end
e1() = expectation(Normal(0, 1), identity, 1e-5)
e2() = expectation2(Normal(0, 1), identity, 1e-5)
compare([e1, e2], 10000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment