对三角形内的均匀随机点进行采样

Sample uniformly random points within a triangle

我想知道如何在 python 中获取三角形内的随机向量,但它似乎比我预期的要难。该平面的坐标如 [a, b]、[x, y]、[u, v](三点):

uv为定义以原点为中心的三角形的向量。通过 this triangle point picking method,可以在 uv 定义的平行四边形内生成随机点。如果点在三角形外,简单地拒绝,反转uv之间对角线的点。

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

图形生成方式:

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)