Created
October 15, 2018 00:13
-
-
Save davidbody/acf400c9c1eff10534c7beac4106e123 to your computer and use it in GitHub Desktop.
Julia code for 12-Oct-2018 Riddler about the goat
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
# 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)) |
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
# 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output on Thinkpad X-1 Carbon Intel i7-7600U @ 2.80GHz x 4 running Ubuntu 18.04.1 LTS: