Generate random locations within a triangular domain

前端 未结 3 868
野趣味
野趣味 2020-12-18 10:36

I want to generate x and y having a uniform distribution and limited by [xmin,xmax] and [ymin,ymax]

The points (x

3条回答
  •  我在风中等你
    2020-12-18 11:37

    Here's some code that generates points uniformly on an arbitrary triangle in the plane.

    import random
    
    def point_on_triangle(pt1, pt2, pt3):
        """
        Random point on the triangle with vertices pt1, pt2 and pt3.
        """
        s, t = sorted([random.random(), random.random()])
        return (s * pt1[0] + (t-s)*pt2[0] + (1-t)*pt3[0],
                s * pt1[1] + (t-s)*pt2[1] + (1-t)*pt3[1])
    

    The idea is to compute a weighted average of the three vertices, with the weights given by a random break of the unit interval [0, 1] into three pieces (uniformly over all such breaks).

    Here's an example usage that generates 10000 points in a triangle:

    pt1 = (1, 1)
    pt2 = (2, 4)
    pt3 = (5, 2)
    points = [point_on_triangle(pt1, pt2, pt3) for _ in range(10000)]
    

    And a plot obtained from the above, demonstrating the uniformity. The plot was generated by this code:

    import matplotlib.pyplot as plt
    x, y = zip(*points)
    plt.scatter(x, y, s=0.1)
    plt.show()
    

    Here's the image:

    And since you tagged the question with the "numpy" tag, here's a NumPy version that generates multiple samples at once. Note that it uses the matrix multiplication operator @, introduced in Python 3.5 and supported in NumPy >= 1.10. You'll need to replace that with a call to np.dot on older Python or NumPy versions.

    import numpy as np
    
    def points_on_triangle(v, n):
        """
        Give n random points uniformly on a triangle.
    
        The vertices of the triangle are given by the shape
        (2, 3) array *v*: one vertex per row.
        """
        x = np.sort(np.random.rand(2, n), axis=0)
        return np.column_stack([x[0], x[1]-x[0], 1.0-x[1]]) @ v
    
    
    # Example usage
    v = np.array([(1, 1), (2, 4), (5, 2)])
    points = points_on_triangle(v, 10000)
    

提交回复
热议问题