2010-12-25

Random Points in a Triangle

Have you ever needed to generate random points in a triangle?

Quite often, such points are needed in compuler simulations and games. I found an article on the subject somwhere and wrote some simple JavaScript code to test it.

Here is the actual algorithm: Given a triangle with vertices A, B and C. Generate two random numbers a and b uniformly between 0 and 1. If the sum a+b is > 1, then set a=1-a and b=1-b. Let c=1-a-b. A random point P distributed uniformly within the triangle is then given by P=aA+bB+cC.

The a, b and c numbers are called the barycentric coordinates of the triangle.

If you have JavaScript enabled in your browser, then you should see a plot below that demonstrates generation of 100 random points within random generated triangles. You can get the source code if you look at the source to this page.