random - 计算触碰 Julia 红线的木棍

标签 random julia counting

我想随机“分散”长度为 1 的棒,如图所示。
我还想数一数碰到红线的木棍。
enter image description here
我的方法是创建在空间中随机定向的归一化向量。
问题是他们都在原点,我也不知道如何识别和计算那些触及红线的人

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
一些评论:
  • 在我的解决方案中,我对 (0,2pi) 范围内的角度进行采样;
  • 我用 x_rangey_range定义散布线条的矩形(x_range 可以是任何东西,但重要的是y_range 是一个整数);
  • 我没有针对速度优化代码,但为了简单起见;在我的 gen_point函数 I 生成一个 2 元素向量,其中包含指示线端点 (x,y) 位置的 2 元素向量; intersects函数 - 如您所见,非常简单:如果两个端点的 y 轴没有相同的整数部分,这意味着该线必须与形式为 y=i 的水平线相交。 ,其中 i是一个整数(我忽略了我们将采样点的情况恰好是整数 y 轴值,因为这是可以忽略不计的);
  • 请注意,您的绘图不正确,因为 x 和 y 轴的缩放比例不同,因此实际上您绘制的线条的长度并非都是 1(这是旁注 - 不影响解决方案)
  • 关于random - 计算触碰 Julia 红线的木棍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68195153/

    相关文章:

    c++ - 哪个熵更高?

    C:生成具有范围内随机数的数组(允许重复)

    plot - 牛虻的颜色不透明度

    python - 递归函数计算数字中数字的出现次数(python)

    PHP:从数组中进行非重复选择

    c# - 二进制搜索算法随机生成的数组项不起作用

    julia - 使用 Julia Plots 设置轴刻度数

    julia - 如何在 Julia 中重复字符串中的单个字符

    MySQL - 在多行输出的情况下计算不同标准的结果

    python - 有没有办法在 python 中将 bincount 与子句一起使用?