Fencepost error
From Free net encyclopedia
In computer programming, a fencepost error (occasionally called a "lamp-post error") is a computer bug involving the discrete equivalent of a boundary condition, often exhibited in programs by iterative loops. This can also occur in a mathematical context, but is not usually named.
The following problem illustrates the error:
- "If you build a fence 100 feet long with posts 10 feet apart, how many posts do you need?"
Many people will intuitively divide 100 by 10 and thus answer 10, but this is incorrect. The fence certainly has 10 sections, but there are 11 posts. The following diagram illustrates this:
( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( ) | | | | | | | | | | | |-----|-----|-----|-----|-----|-----|-----|-----|-----|-----| | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | | | | | | | | | | | | |-----|-----|-----|-----|-----|-----|-----|-----|-----|-----| 1 2 3 4 5 6 7 8 9 10 11
In computing, suppose you have a long list or array of items, and want to process items m through n; how many items are there? The obvious answer is n−m, but that is off by one; the right answer is n−m+1. The "obvious" formula exhibits a fencepost error. (This is the motivation behind the representation of ranges in computing by half-open intervals: the range from m to n (both inclusive) is very often represented by the range from m (inclusive) to n + 1 (exclusive) to avoid fencepost errors.)
Note that not all off-by-one errors are fencepost errors. The game of musical chairs involves a catastrophic off-by-one error where n people try to sit in n−1 chairs, but this is not a fencepost error (see also pigeonhole principle). Fencepost errors come from counting things rather than the spaces between them, or vice versa, or by neglecting to consider whether one should count one or both ends of a row.
A rare secondary meaning is an error induced by unexpected regularities in input values, which can (for instance) completely thwart a theoretically efficient binary tree or hash function implementation. The error here involves the difference between expected and worst case behaviours of an algorithm.
See also
An earlier version of this article was based on fencepost error at FOLDOC, used with permission.de:Zaunpfahlproblem