Skip to content

Instantly share code, notes, and snippets.

@davidbody
Created October 15, 2018 00:13
Show Gist options
  • Save davidbody/acf400c9c1eff10534c7beac4106e123 to your computer and use it in GitHub Desktop.
Save davidbody/acf400c9c1eff10534c7beac4106e123 to your computer and use it in GitHub Desktop.
Julia code for 12-Oct-2018 Riddler about the goat
# https://fivethirtyeight.com/features/so-you-want-to-tether-your-goat-now-what/
# James Jones's Python solution translated to Julia
using Formatting
function randPoint()
randr = sqrt(rand())
theta = rand() * 2 * π
randr * cos(theta), randr * sin(theta)
end
function randSeq(n)
(randPoint() for i = 1:n)
end
function grazeable(x, y, r)
(x - 1)^2 + y^2 <= r^2
end
function trial(n, r)
grazeables = sum([1 for (x, y) in randSeq(n) if grazeable(x, y, r)])
grazeables / n
end
n_trials = 100000000
println("Performing ", format(n_trials, commas = true), " trials ...")
# Solution is ~ 1.16
@time println(trial(n_trials, 1.16))
# https://fivethirtyeight.com/features/so-you-want-to-tether-your-goat-now-what/
# James Jones's Python solution translated to Julia
# Parallel version
using Distributed
using Formatting
@everywhere function randPoint()
randr = sqrt(rand())
theta = rand() * 2 * π
randr * cos(theta), randr * sin(theta)
end
@everywhere function grazeable(x, y, r)
(x - 1)^2 + y^2 <= r^2
end
@everywhere function trialp(n, r)
grazeables = @distributed (+) for i = 1:n
x, y = randPoint()
grazeable(x, y, r) ? 1 : 0
end
grazeables / n
end
n_trials = 100000000
println("Performing ", format(n_trials, commas = true), " trials using ", nprocs(), " processes...")
# Solution is ~ 1.16
@time println(trialp(n_trials, 1.16))
@davidbody
Copy link
Author

Output on Thinkpad X-1 Carbon Intel i7-7600U @ 2.80GHz x 4 running Ubuntu 18.04.1 LTS:

➜  julia --version
julia version 1.0.1
➜  julia graze.jl              
Performing 100,000,000 trials ...
0.50088784
  4.532897 seconds (783.82 k allocations: 453.908 MiB, 1.97% gc time)

➜  julia --procs auto grazep.jl
Performing 100,000,000 trials using 5 processes...
0.50085113
  2.687030 seconds (2.44 M allocations: 122.870 MiB, 0.67% gc time)

@davidbody
Copy link
Author

The Python version on which the above is based takes over 90 seconds to do 100 million trials.

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