Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am attempting to write a function (programming, not mathematics) which calculates the shortest distance between two points on a toroid. I got the following formula from StackOverflow, but I don't recognize the min portion. Can someone explain that to me, please?

sqrt(min(|x1 - x2|, w - |x1 - x2|)^2 + min(|y1 - y2|, h - |y1-y2|)^2)
share|cite|improve this question
up vote 3 down vote accepted

As explained in the question you reference, this toroid is created by identifying the sides of a rectangle $w$ units wide in the x direction and $h$ units high in the y direction. So assume you have two points $(x_1, y)$ and $(x2, y)$, at the same height and let $x_2>x_1$. To get from $(x_2, y)$ to $(x_1, y)$ you can either go left by a distance $(x_2-x_1)$, or you can go right (off the edge) and come around a distance of $(w-x_2)+x_1$. The min just picks smaller of these. Similarly in y.

share|cite|improve this answer
Thanks a lot. I read through the other answers and figured that out, but I appreciate your answer. – Caleb Thompson Dec 10 '10 at 18:58

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.