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

Okh*_*ial 4 language-agnostic random geometry

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

我想做的事

Mat*_*haq 7

令u和v为定义以原点为中心的三角形的向量。通过这种三角形点选取方法,可以在u和定义的平行四边形内生成随机点v。如果点位于三角形之外,则只需拒绝或u反转关于和之间对角线的点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
Run Code Online (Sandbox Code Playgroud)

三角形

通过以下方式生成的图:

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)
Run Code Online (Sandbox Code Playgroud)