Proofs: Geohash
These are the human proofs of Geohash, at full length.
Geohash encodes the interleaved bits of the cell that holds the point full
This proof shows: correctness, termination.
We use the names of the pseudocode GEOHASH-ENCODE, with and . Let be the number of passes of the loop of line L3 so far, so . Write and for the numbers of longitude and latitude bits among the first bits. For an integer and a value in a range , let
the index of the part of that holds when the range is cut into equal parts, with the top value in the top part. Write over and over .
Claim. The output has characters, and its bits are , where the subsequence is the binary form of with digits and is the binary form of with digits. The point lies in the cell given by the final intervals.
Invariant. At the test of line L3, after passes:
- and , and , with unless .
- The same holds for , with , , and .
- The longitude bits produced so far, in order, are the binary form of with digits, and the latitude bits are the binary form of with digits.
- is the number whose binary form is the last bits produced, , and holds the first bits, five per character, as the indices of its characters in .
- is true exactly when is even.
Initialization. At , line L1 sets the full ranges, and , so parts 1 and 2 hold, with or . No bits exist, so part 3 holds. Line L2 sets empty, , and true, so parts 4 and 5 hold.
Maintenance. Take a pass with even, so by part 5 line L4 runs and cuts the longitude interval; the odd case is the same with line L5 and the latitude. The pass makes bit , an odd position, and , . Let and .
- If , the bit is 1 and the new interval is . Then lies in , and it equals only when , which by part 1 happens only when , where the minimum in caps the index. So .
- If , the bit is 0, the new interval is , and the same computation gives a value in , so , and is strictly below the new upper end.
In both cases the new interval has the form of part 1 for and , it holds , and the upper end stays strict unless it is . The latitude is not changed and is not changed, so part 2 holds. Appending a bit to the binary form of gives , so part 3 holds. Line L4 sets , which appends the bit to the binary form of , and line L6 adds 1 to . If becomes 5, line L7 appends the character of index , which holds the last five bits, and resets and to 0. So part 4 holds. Line L6 flips , and is odd, so part 5 holds.
Termination. Each pass adds 1 to . Since by part 4, grows by one every five passes, so after exactly passes and the loop stops. At that point , so all bits are in . By part 3 they are the bits of the claim, and by parts 1 and 2 the point lies in the final intervals.
Prefix property. The bits of a pass do not depend on : the loop for length runs the same passes as the loop for length and then more. So the geohash of length is the prefix of length of the geohash of length , and the cell of the longer string lies inside the cell of the shorter one, since each pass keeps half of an interval.