我想随机“分散”长度为 1 的棒,如图所示。
我还想数一数碰到红线的木棍。
我的方法是创建在空间中随机定向的归一化向量。
问题是他们都在原点,我也不知道如何识别和计算那些触及红线的人
a = [randn(), randn()];
line = a/norm(a) # Normalized vector in random direction
最佳答案
以下是使用模拟解决问题的方法之一:
julia> using Statistics
julia> function gen_point()
α = rand() * 2π
range_x = 5 # anything as your lines are horizontal
range_y::Int = 5 # must be a positive integer
@assert range_y >= 1
x0 = [rand() * range_x, rand() * range_y]
xd = [cos(α), sin(α)]
return (x0, x0 .+ xd)
end
gen_point (generic function with 1 method)
julia> intersects(point) = floor(point[1][2]) != floor(point[2][2])
intersects (generic function with 1 method)
julia> mean((intersects(gen_point()) for _ in 1:100_000))
0.63731
julia> 2/π # our simulation recovers the theoretical result
0.6366197723675814
一些评论:x_range
和 y_range
定义散布线条的矩形(x_range
可以是任何东西,但重要的是y_range
是一个整数); gen_point
函数 I 生成一个 2 元素向量,其中包含指示线端点 (x,y) 位置的 2 元素向量; intersects
函数 - 如您所见,非常简单:如果两个端点的 y 轴没有相同的整数部分,这意味着该线必须与形式为 y=i
的水平线相交。 ,其中 i
是一个整数(我忽略了我们将采样点的情况恰好是整数 y
轴值,因为这是可以忽略不计的); 关于random - 计算触碰 Julia 红线的木棍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68195153/