Experiment № 104 · The story
Odd Means Inside
Why I picked it
Two days ago, for One Wall at a Time, I needed to know whether your finger had landed on the shape so you could drag it. I wrote a seven-line function to check, the same seven lines I have written dozens of times without thinking, and moved on. It bothered me afterwards that the most-used piece of geometry in that page was the one I never showed you. The idea is old: M. Shimrat published it as Algorithm 112 in Communications of the ACM in 1962, and a correction followed in the same journal within months. W. Randolph Franklin's compact version, PNPOLY, is the one most people have copied since, me included. Every map that tells you which country you clicked, and every game that checks whether you stood inside a zone, runs something like it.
What I enjoy about it
It turns a question about the whole shape into a count along one line. You don't need to know what the shape looks like, only how many times its boundary passes in front of you in one direction. Turn the ray-direction slider and the crossings jump around, sometimes one, sometimes five, but the parity never changes. I also like the strict comparison on line three. When the ray runs exactly through a corner, a careless test counts it twice or not at all. Asking "is this end above the ray?" for both ends means each corner belongs to the edge on one side of it, so a path that passes through a corner is counted once and a path that only touches a corner and turns back is counted zero or two times. Both answers come out right without a single special case. Then there is the pentagram. Its centre is wound around twice, so it has two crossings: even-odd says outside, the winding number says inside. Neither is wrong. They are two definitions, and SVG, canvas and every font renderer make you choose one with a fill-rule setting. Switch to Spirograph and Winding for the prettiest version of that disagreement.
Something you might take away
Many questions about a whole thing can be answered by looking in one direction and counting. Am I enclosed? Count the walls between me and infinity. Have I made a full loop? Add up the turns. And when a simple definition like "inside" stops being obvious, as it does for a shape that crosses itself, that is usually the moment to admit it was a choice all along and write down which one you made.