julia - 模拟一道概率题: 3 independent dice

标签 julia probability montecarlo

我决定模拟一个教科书上的概率题:

Three fair dice are rolled independently, what is the probability that one dice shows 6 and the other two show two non-equal numbers (and neither is equal 6)

假设骰子是公平的,因此“理论”答案将是 $\frac{\binom{5}{2}}{\binom{6}{3}}=0.5$;我决定在 Julia 中对此进行模拟,这是我为此编写的函数:

function simulation(n_experiments::Int = 100)
    dice = [DiscreteUniform(1, 6) for i in 1:3] # 3 independent fair dice
    successes = 0
    for trial in 1:n_experiments
        experiment = rand.(dice) # roll
        one_six = sum(r == 6 for r in experiment) == 1 # check if there is only one "6"
        others = filter(num -> num != 6, experiment)
        no_duplicates = length(Set(others)) == 2 # check if other two are distinct
        if no_duplicates
            if one_six
                successes += 1 # count "success"
            end
        end
    end
    return successes / n_experiments
end

我预计这会返回 0.5 左右的值,但实际上它在大约 10^5 次迭代后返回 ~0.27 (n_experiments)。谁能帮我找出代码中的缺陷?

最佳答案

我认为你的代码是正确的,但你的数学错误:

julia> function simulation(n_experiments=100)
           chains = rand.(fill(DiscreteUniform(1, 6), 3), n_experiments)
           return (1/n_experiments) * mapreduce(+, chains...) do d1, d2, d3
               (d1 == 6 && d2 != 6 && d3 != 6 && d2 != d3) || (d1 != 6 && d2 == 6 && d3 != 6 && d1 != d3) || (d1 != 6 && d2 != 6 && d3 == 6 && d1 != d2)
           end
       end
simulation (generic function with 1 method)

julia> simulation(10_000)
0.279

julia> count(Iterators.product(1:6, 1:6, 1:6)) do (d1, d2, d3)
           (d1 == 6 && d2 != 6 && d3 != 6 && d2 != d3) || (d1 != 6 && d2 == 6 && d3 != 6 && d1 != d3) || (d1 != 6 && d2 != 6 && d3 == 6 && d1 != d2)
       end 
60

julia> 60 / 6^3
0.2777777777777778

我希望看到一种简洁的方式来对条件进行编码。由于分配,我避免了您的变体,而我的变体只是冗长以确保它是正确的——但是太长了……


附录

这是具有生成条件的优化变体。与问题无关,但因为我觉得它很酷。条件公式归功于 Bogumił。

julia> @generated function condition(xs::NTuple{N,<:Any}) where {N}
           offdiagonals = ((i, j) for i = 1:N for j = (i+1):N)
           names = Symbol.(:xs, 1:N)
           assignments = [:($(names[i]) = xs[$i]) for i = 1:N]
           comparisons = [:($(names[i]) != $(names[j])) for (i, j) in offdiagonals]
           condition = Expr(:&&, :(maximum(xs) == 6), comparisons...)
           return quote
               $(assignments...)
               $condition
           end
       end
condition (generic function with 1 method)

julia> @code_warntype condition((1,2,3))
MethodInstance for condition(::Tuple{Int64, Int64, Int64})
  from condition(xs::Tuple{Vararg{var"#s17", N}} where var"#s17") where N in Main at REPL[71]:1
Static Parameters
  N = 3
Arguments
  #self#::Core.Const(condition)
  xs::Tuple{Int64, Int64, Int64}
Locals
  xs3::Int64
  xs2::Int64
  xs1::Int64
Body::Bool
1 ─       (xs1 = Base.getindex(xs, 1))
│         (xs2 = Base.getindex(xs, 2))
│         (xs3 = Base.getindex(xs, 3))
│   %4  = Main.maximum(xs)::Int64
│   %5  = (%4 == 6)::Bool
└──       goto #7 if not %5
2 ─ %7  = (xs1 != xs2)::Bool
└──       goto #6 if not %7
3 ─ %9  = (xs1 != xs3)::Bool
└──       goto #5 if not %9
4 ─ %11 = (xs2 != xs3)::Bool
└──       return %11
5 ─       return false
6 ─       return false
7 ─       return false


julia> function simulation(n_experiments=100)
           (1/n_experiments) * sum(1:n_experiments) do _
               dice = (rand(1:6), rand(1:6), rand(1:6))
               condition(dice)
           end
       end
simulation (generic function with 2 methods)

julia> @time simulation(10_000_000)
  0.157303 seconds
0.2777498

这根本没有分配。 sum 与手动循环一样快!

关于julia - 模拟一道概率题: 3 independent dice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71007705/

相关文章:

python - 如何构建程序以使用扫雷艇配置

r - R中二项式数据的置信区间

arrays - 获取子例程返回引用数组的指针,然后在 main 中取消引用它(在 C 中)

python - Python 中的 Q : Expected number of coin tosses to get N heads in a row,。我的代码给出的答案与已发布的正确答案不匹配,但不确定原因

julia - Julia DataFrame 中一列的累积总和

python - R/Python/Julia 中 Matlab 的类型转换函数的等价物是什么

arrays - Julia 中的push!() 和append!() 方法的效率如何?

c++ - 适当的 boolean 随机生成器(伯努利分布)

c++ - 使用随机数生成器为随机数生成器池播种

matrix - 在 Julia 中构造随机正交矩阵序列