Created
March 22, 2013 16:54
-
-
Save johnmyleswhite/5222915 to your computer and use it in GitHub Desktop.
Comparing two ways of computing expectations in Julia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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