← Back to index

Uniform random point in a triangle

Pick two random numbers in [0, 1]. If their sum is greater than 1, fold them back by replacing each with 1 − itself — this maps the upper-right half of the unit square onto the lower-left half, which corresponds exactly to the triangle in barycentric coordinates. The result is uniform with no rejection waste.

See also: Point-in-triangle — uses the same barycentric coordinates as a hit test.

Pseudocode

u = random()
v = random()
if u + v > 1:
    u = 1 - u
    v = 1 - v
p = a + (b - a) * u + (c - a) * v

Source

function uniformInTriangle(a, b, c) {
    let u = Math.random()
    let v = Math.random()
    if (u + v > 1) { u = 1 - u; v = 1 - v }
    return {
        x: a.x + (b.x - a.x) * u + (c.x - a.x) * v,
        y: a.y + (b.y - a.y) * u + (c.y - a.y) * v,
    }
}