pythonrandomgeometry

Sample uniformly random points within a triangle


I would like to know how to get random vectors inside a triangle, in python, but it seemed more difficult than I expected. The plane would have coordinates like [a, b], [x, y], [u, v] (three points):

What I want to do


Solution

  • Let u and v be vectors defining a triangle centered at the origin. By this triangle point picking method, one can generate random points within a parallelogram defined by u and v. If points are outside the triangle, simply reject, or invert the points about the diagonal between u and v.

    import random
    
    def uniform_triangle(u, v):
        while True:
            s = random.random()
            t = random.random()
            in_triangle = s + t <= 1
            p = s * u + t * v if in_triangle else (1 - s) * u + (1 - t) * v
            yield p
    

    triangle

    Figure generated via:

    from itertools import islice
    import matplotlib.pyplot as plt
    import numpy as np
    
    triangle = np.array([
        [1, 2],
        [3, 8],
        [7, 5],
    ])
    
    it = uniform_triangle(
        triangle[1] - triangle[0],
        triangle[2] - triangle[0],
    )
    
    points = np.array(list(islice(it, 0, 1000)))
    points += triangle[0]
    
    fig, ax = plt.subplots()
    ax.scatter(points[:, 0], points[:, 1], s=1)
    fig.savefig("triangle.png", dpi=200)