Random samples from a tetrahedron

Exactly one month ago I wrote about sampling points from a triangle. This post will look at the three dimensional analog, sampling from a tetrahedron. The generalization to higher dimensions works as well.

Sampling from a triangle

In the triangle post, I showed that a naive approach doesn’t work but a variation does. If the vertices of the triangle are AB, and C, then the naive approach is to generate three uniform random numbers, normalize them, and use them to form a linear combination of the vertices. That is, generate

r1r2r3

uniformly from [0, 1], then define

r1′ = r1/(r1r2r3)
r2′ = r2/(r1r2r3)
r3′ = r3/(r1r2r3)

and return as a random sample the point

r1′ A + r2′ B + r3C.

This oversamples points near the middle of the triangle and undersamples points near the vertices. But everything above works if you replace uniform samples with exponential samples.

Sampling from a tetrahedron

The analogous method works for a tetrahedron with vertices ABC, and D. Generate exponential random variables ri for i = 1, 2, 3, 4. Then normalize, defining each ri′ to be ri divided by the sum of all the ri s. Then the random sample is

r1′ A + r2′ B + r3C + r4D.

In the case of the triangle, it was easy to visualize that uniformly generated rs did not lead to uniform samples of the triangle, but that exponentially generated rs did. This is harder to do in three dimensions. Even if the points were uniformly sampled from a tetrahedron, they might not look uniformly distributed from a given perspective.

So how might we demonstrate that our method works? One approach would be to take a cube inside a tetrahedron and show that the proportion of samples that land inside the cube is what we’d expect, namely the ratio of the volume of the cube to the volume of the tetrahedron.

This brings up a couple interesting subproblems.

  1. How do we compute the volume of a tetrahedron?
  2. How can we test whether our cube lies entirely within the tetrahedron?

Volume of a tetrahedron

To find the volume of a tetrahedron, form a matrix M whose columns are the vectors from three of the vertices to the remaining vertex. So we could take AD, BD, and CD. The volume of the tetrahedron is the determinant of M divided by 6.

Testing whether a cube is inside a tetrahedron

A tetrahedron is convex, and so the line segment joining any two points inside the tetrahedron lies entirely inside the tetrahedron. It follows that if all the vertices of a cube are inside the a tetrahedron, the entire cube is inside.

So this brings us to the problem of testing whether a point is inside a tetrahedron. We can do this by converting the coordinates of the point to barycentric coordinates, then testing whether all the coordinates are non-negative and add to 1.

Random sampling illustration

I made up four points as vertices of a tetrahedron.

import numpy as np

A = [0, 0, 0]
B = [5, 0, 0]
C = [0, 7, 0]
D = [0, 1, 6]
A, B, C, D = map(np.array, [A, B, C, D])

For my test cube I chose the cube whose vertex coordinates are all combinations of 1 and 2. So the vertex nearest the origin is (1, 1, 1) and the vertex furthest from the origin is (2, 2, 2). You can verify that all the vertices are inside the tetrahedron, and so the cube is inside the tetrahedron.

The tetrahedron has volume 35, and the cube has volume 1, so we expect 1/35th of the random points to land inside the cube. Here’s the code to sample the tetrahedron and calculate the proportion of points that land in the cube.

from scipy.stats import expon

def incube(v):
    return 1 <= v[0] <= 2 and 1 <= v[1] <= 2 and 1 <= v[2] <= 2

def good_sample(A, B, C, D):
    r = expon.rvs(size=4)
    r /= sum(r)
    return r[0]*A + r[1]*B + r[2]*C + r[3]*D

def bad_sample(A, B, C, D):
    r = np.random.random(size=4)
    r /= sum(r)
    return r[0]*A + r[1]*B + r[2]*C + r[3]*D

N = 1_000_000

badcount  = 0
goodcount = 0

for _ in range(N):
    v = bad_sample(A, B, C, D)
    if incube(v):
        badcount += 1        
    v = good_sample(A, B, C, D)
    if incube(v):
        goodcount += 1

print(badcount/N, goodcount/N, 1/35)

This produced

0.094388 0.028372 0.028571…

The good (exponential) method match the expected proportion to three decimal places but the bad (uniform) method put about 3.3 times as many points in the cube as expected.

Note that three decimal agreement is about what we’d expect via the central limit theorem since 1/√N = 0.001.

If you’re porting the sampler above to an environment where you don’t a function for generating exponential random samples, you can roll your own by returning −log(u) where u is a uniform sample from [0. 1].

More general 3D regions

After writing the post about sampling from triangles, I wrote a followup post about sampling from polygons. In a nutshell, divide your polygon into triangles, then randomly select a triangle in proportion to its area, then sample with that triangle. You can do the analogous process in three dimensions by dividing a general volume into tetrahedra.

Conway’s pinwheel tiling

John Conway discovered a right triangle that can be partitioned into five similar triangles. The sides are in proportion 1 : 2 : √5.

You can make a larger similar triangle by making the entire triangle the central (green) triangle of a new triangle.

Here’s the same image with the small triangles filled in as in the original.

Repeating this process creates an aperiodic tiling of the plane.

The tiling was discovered by Conway, but Charles Radin was the first to describe it in a publication [1]. Radin attributes the tiling to Conway.

Alternate visualization

It would be easiest to illustrate the tiling if we were standing together in a room and placing new triangles on the floor, watching the tiling expand. Given the limitations of a screen, it may be easier to visualize subdividing the triangle rather than tiling the plane.

Imagine the smallest triangles are a constant size and at each step we’re viewing the process from further away. We see a constant size outer triangle at each step, but the triangle is growing and covering the plane.

Here’s an animated GIF of the process.

 

Related posts

[1] Charles Radin. “The Pinwheel Tilings of the Plane.” Annals of Mathematics, vol. 139, no. 3, 1994, pp. 661–702.

More triangle inequalities

Yesterday I wrote about a triangle inequality discovered by Paul Erdős.

Let P be a point inside a triangle ABC. Let xyz be the distances from P to the vertices and let pqr, be the distances to the sides. Then Erdős’ inequality says

x + y + z ≥ 2(p + q + r).

Using the same notation, here are four more triangle inequalities discovered by Oppenheim [1].

  • px + qy + rz ≥ 2(qr + rp + pq)
  • yz + zx + xy ≥ 4(qr + rp + pq),
  • xyz ≥ 8pqr
  • 1/p+ 1/q + 1/r ≥ 2(1/x + 1/y + 1/z)

[1] A. Oppenheim. The Erdös Inequality and Other Inequalities for a Triangle. The American Mathematical Monthly. Vol. 68, No. 3 (Mar., 1961), pp. 226–230

Random samples from a polygon

Ted Dunning left a comment on my post on random sampling from a triangle saying you could extend this to sampling from a polygon by dividing the polygon into triangles, and selecting a triangle each time with probability proportional to the triangle’s area.

To illustrate this, let’s start with a irregular pentagon.

To pick a point inside, I used the centroid, the average of the vertices. Connecting the centroid to each of the vertices splits the pentagon into triangles. (Here I implicitly used the fact that this pentagon is convex. The centroid of a non-convex polygon could be outside the polygon.)

We can find the area of the triangles using Heron’s rule.

Here’s what we get for random samples.

A triangle inequality by Erdős

Plane geometry has been studied since ancient times, and yet new results keep being discovered millennia later, including elegant results. It’s easy to come up with a new result by proving a complicated theorem that Euclid would not have cared about. It’s more impressive to come up with a new theorem that Euclid would have understood and found interesting.

Paul Erdős conjectured another triangle inequality in 1935 which was proved by Mordell and Barrow in 1937 [1].

Let P be a point inside a triangle ABC. Let x, y, z be the distances from P to the vertices and let p, q, r, be the distances to the sides. Then

xyz ≥ 2(pqr)

with equality only if P is the center of an equilateral triangle [2]. In the figure above, the theorem says the dashed blue lines together are more than twice as long as the solid red lines.

How far apart are the left and right sides of the inequality? This was the motivation for the previous post on selecting random points from a triangle. I wanted to generate random points and compare the two sides of the Erdős-Mordell-Barrow inequality.

We can visualize the inequality by generating random points inside the triangle and plotting the points with a color that indicates the inequality gap, darker blue corresponding to a larger gap.

This shows the inequality is sharper in the middle of the triangle than near the vertices.

[1] Problem 3740, American Mathematical Monthly, 44 (1937) 252-254.

[2] You could interpret this as a theorem comparing barycentric and trilinear coordinates.

Intuition for Pick’s Theorem

Pick’s theorem is a surprising and useful to find the area of a region formed by connecting dots on a grid. The area is simply

A = ip/2 − 1

where i is the number of dots in the interior and p is the number of dots on the perimeter.

Example

For example, the in the figure below there are 11 black dots on the perimeter and 17 blue dots in the interior.

Therefore Pick’s theorem says the area of the figure is 17 + 11/2 − 1 =  21½.

Intuition

It makes sense that the area would be approximately i if the figure is very large. But why do you need to add half the dots on the perimeter and why do you subtract 1?

Pick’s theorem is simple, but it isn’t obvious. If it were obvious, someone closer to the time of Descartes (1596–1650) would have discovered it. Instead, the theorem was discovered by Georg Alexander Pick in 1899. However, the theorem is fairly obvious for a rectangle, and this post will illustrate that case. For a rectangle, you can easily see why you need to add half the perimeter dots and subtract 1.

Rectangular case

Imagine an m by n rectangular array of dots. If you were to draw a frame around those dots with the corners of the rectangle being exactly between dots, the area would be mn, the number of dots inside the frame.

Pick’s theorem does not apply here because the corners of our frame do not lie on the grid. So let’s shift our grid down and to the left so that its corners do lie on the grid.

Now some of our original dots, marked in blue, are on the perimeter of the frame. We could add the number of dots on the perimeter to correct for this, but that would be too much because the blue dots on the perimeter are only on the left and top sides. Each has a reflection on the right and bottom, marked with red dots. So we shouldn’t add all the dots on the perimeter, but only half the dots on the perimeter.

But that still overcounts slightly. There are two dots on the perimeter that do not correspond to a blue dot or to the reflection of a blue dot. These are the hollow circles in the top right and bottom left corners. So when we take half the perimeter, we need to subtract 1 to account for half of this pair of dots.

This doesn’t prove Pick’s theorem in general, but it does prove it for rectangular regions. Even if we can’t see why the formula generalizes to more complicated regions, we can be grateful that it does.

Related posts

Roundest regular solid

dodecahedron and icosahedron

Iconjack posted on X today

(Possibly) surprising fact: a regular dodecahedron is rounder than a regular icosahedron.

You might reasonably suppose that having more sides would result in a rounder figure, so a figure with 20 sides should be rounder than a figure with 12 sides. But it’s the other way around.

Discrete curvature

Here’s one way to see the statement above. In a dodecahedron, three pentagons come together at each vertex. The interior angles of a pentagon have 108°. If you were to take the three pentagons, cut a slit long one slide, and push them flat on to a plane, there would be a gap of

360° − 3 × 108° = 36°.

This gap is known as the angle defect and is the discrete analog of curvature.

In an icosahedron you have five triangles coming together at a point. So if you were to push the five triangles at a vertex down to a point, there would be a gap (angle defect) of

360° − 5 × 60° = 60°.

The larger angle defect means the shape is less round at a vertex.

For completeness, the angle defect of a cube is 90°. For an octahedron it’s 120° and for a tetrahedron it’s 180°.

Dihedral angles

Angle defect is the standard way to measure how round a polyhedron is. It focuses on how faces fit together at a vertex. But we could instead focus on how faces fit together at an edge. The angle between two adjacent faces is the dihedral angle.

The faces of an icosahedron come meet at an angle of approximately 138.19°. For a dodecahedron, the angle is 116.57°. So the icosahedron is rounder in the sense that the faces come together at an angle closer to 180°.

The dihedral angles for the octahedron, cube, and tetrahedron are 109.47°, 90°, and 70.53°.

Related posts

Finding tangent circles

If three circles are all tangent to each other, you can find two more circles that are tangent to all three, and the equation for finding these new circles is remarkably elegant. This is Descartes’ theorem.

Two tangent circles

To illustrate Descartes’ theorem, we first need three mutually tangent circles. Drawing two mutually tangent circles is easy. We choose our coordinate system so that the first circle is centered at the origin

O1 = (x1, y1) = (0, 0)

and the center of the second circle is on the x-axis. If the two circles have radii r1 and r2, then the center of the second circle is at

O2 = (x2, y2) = (r1 + r2, 0).

I’ve assumed that the second circle is outside the first. You could have a tangent circle inside another circle, but to illustrate Descartes’ theorem we need circles that are externally tangent.

Three tangent circles

Now we pick the radius of the third circle to be r3. The center of this circle must belong to a circle of radius r1 + r3 centered at O1 and to a circle of radius r2 + r3 centered at O2. I went over finding the point(s) of intersection of two circles here.

For illustration I chose r1 = 2, r2 = 1, and r3 = 2.8. Using the code from the aforementioned post I found

(x3, y3) = (2.93333333 3.79941516)

Here’s a plot.

Four tangent circles

Now we’re in a position to state and illustrate Descartes’ theorem. The theorem is most easily stated in terms of signed curvatures.

The curvature of a circle of radius r is 1/r. Big circles have small curvature and small circles have big curvature.

For Descartes’ theorem we need to use signed curvatures, taking the sign to be positive if circles are externally tangent and negative if the circles are internally tangent. The signed curvatures of our three circles are positive, that is

ki = 1/ri

for i = 1, 2, and 3. But Descartes’ theorem will give us two circles, one between the three given circles and one surrounding them, corresponding to a positive and negative solution for k4.

Finding the radii

Now we can state Descartes’ theorem [1]:

(k1 + k2 + k3 + k4)² = 2(k1² + k2² + k3² + k4²)

This gives us a quadratic equation for k4 with two solutions:

k4 = k1 + k2 + k3 ±2(k1k2 + k2k3 + k1k3)½.

Finding the centers

Now we know the radii of our tangent circles, but not the centers. For this we view the circles as living in the complex plane with centers zi. Then the centers satisfy a theorem analogous to the one satisfied by the curvatures.

(k1z1 + k2z2 + k3z3 + k4z4)² = 2(k1²z1² + k2²z2² + k3²z3² + k4²z4²)

In other words, the curvature-center products satisfy the same equation as the curvatures.

I’m unclear on the history here, but I don’t believe Descartes had a formula for the centers of the circles. He certainly did not have the formula above using complex numbers [2].

Here’s a plot of the two circles guaranteed by Descartes’ theorem.

[1] The Soddy-Gossett theorem generalizes Descartes theorem to the case of n + 2 spheres in ℝn. The square of the sums of the curvatures equals n the sum of the curvatures squared.

[2] Jeffrey C. Lagarias, Colin L. Mallows, Allan R. Wilks. Beyond the Descartes circle theorem. https://arxiv.org/abs/math/0101066v1

Primitive Pythagorean triangles with the same area

A Pythagorean triangle is a right triangle with integer sides. A primitive Pythagorean triangle is one in which the sides have no factor in common. For example a triangle with sides (30, 40, 50) is a Pythagorean triangle but not a primitive Pythagorean triangle.

It is possible for two primitive Pythagorean triangles to have the same area. The smallest example is (20, 21, 29) and (12, 35, 37). Both have area 210.

It’s also possible for three primitive Pythagorean triangles to have the same area, but the smallest example is much larger. The triangles (4485, 5852, 7373), (1380, 19019, 19069), and (3059, 8580, 9109) all have area 13123110, discovered by C. L. Shedd in 1945.

Nobody has found an example of four primitive Pythagorean triangles having the same area. I don’t know whether it’s been settled whether such triangles exist. But it has been proven that if they exist, they have area greater than 9.3 × 1024. See OEIS A093536.

Incidentally, the triangle (20, 21, 29) came up in the post Do perimeter and area determine a triangle? from February of this year.

Transmission Obstacles and Ellipsoids

Suppose you have a radio transmitter T and a receiver R with a clear line of sight between them. Some portion the signal received at R will come straight from T. But some portion will have bounced off some obstacle, such as the ground.

The reflected radio waves will take a longer path than the waves that traveled straight from T to R. The worst case for reception is when the waves traveling a longer path arrive half a period later, i.e. 180° out of phase, canceling out part of the signal that was received directly.

We’d like to describe the region of space that needs to be empty in order to eliminate destructive interference, i.e. signals 180° out of phase. Suppose T and R are a distance d apart and the wavelength of your signal is λ. An obstacle at a location P can cause signals to arrive exactly out of phase if the distance from T to P plus the distance from P to R is d + λ/2.

So we’re looking for the set of all points such that the sum of their distances to fixes points is a constant. This is the nails-and-string description of an ellipse, where the nails are a distance d apart and the string has length d + λ/2.

That would be a description of the region if we were limited to a plane, such as a plane perpendicular to the ground and containing the transmitter and receiver. But signals could reflect off an obstacle that’s outside this plane. So now we need to imagine being able to move the string in three dimensions. We still get all the points we’d get if we were restricted to a plane, but we also get their rotation about the axis running between T and R.

The region we’re describing is an ellipsoid, known as a Fresnel ellipsoid or Fresnel zone.

Suppose we choose our coordinates so that our transmitter T is located at (0, 0, h) and our receiver R is located at (d, 0, h). We imagine a string of length d + λ/2 with endpoints attached to T and R. We stretch the string so it consists of two straight segments. The set of all possible corners in the string traces out the Fresnel ellipsoid.

Greater delays

If reflected waves are delayed by exactly one period, they reinforce the portion of the signal that arrived directly. Signals delayed by an even multiple of a half-period cause constructive interference, but signals delayed by odd multiples of a half-period cause destructive interference. The odd multiples matter most because we’re more often looking to avoid destructive interference rather than seeking out opportunities for constructive interference.

If you repeat the exercise above with a string of length d + λ you have another Fresnel ellipsoid. The foci remain the same, i.e. T and R, but this new ellipsoid is bigger since the string is longer. This ellipsoid represents locations where a signal reflected at that point will arrive one period later than a signal traveling straight. Obstacles on the surface of this ellipsoid cause constructive interference.

We can repeat this exercise for a string of length d + nλ/2, where odd values of n correspond to regions of destructive interference. This gives us a set of confocal ellipsoids known as the Fresnel ellipsoids.

Related posts