Hello, While working on another patch (an ordering index scan that hands its ORDER BY values to the target list [1]) I found a pre-existing inexactness in the point-to-box distance operator.
box_closept_point(), behind <->(point, box), <->(box, point) and ##(point, box), found the closest point by projecting the point onto each edge's line with the generic line-segment code. That code compares slopes and intersections with the EPSILON fuzz, so for a point near an edge's line it can pick the wrong edge or corner. The point (0.9999996, 2) is 1 from the box ((0,0),(1,1)), but the operator said 1.00000000000008, and (1e-300, -1e-300) is 1e-300 from ((2,2),(0,0)), but the operator said 1.41421356237e-300, the distance to the corner. The GiST and SP-GiST box opclasses compute the distance to a box their own way, exactly, and order a nearest-neighbor scan by that. So an index scan could return rows in an order the operator disagrees with: for the point above, a box 1.00000000000004 away came after the box the operator put at 1.00000000000008. A box's edges are parallel to the axes, so the closest point is the point clamped to the box, and the distance follows from that with no line arithmetic. This patch does that, and has GiST's and SP-GiST's distance to a box (computeDistance() for non-leaf entries and point_box_distance()) call the same function, so the index orders by the operator's own distance. SP-GiST's version now errors on overflow, as GiST's and the operator always did, and returns NaN when any coordinate is NaN. A coordinate inside the box's range contributes nothing to the distance, even an infinite one; computing the per-axis delta directly rather than subtracting the clamped point keeps Infinity minus Infinity from becoming NaN, which would otherwise break a nearest-neighbor scan's ordering (NaN sorts after everything, so it stops being a lower bound). box.sql covers the infinite and NaN cases. The geometry regression test changes in four rows, all corrections: the 1e-300 distance above, its closest point, and the closest points to (1e+300,Infinity) and (Infinity,1e+300), which are now the box's top right corner rather than its top left. The patch applies to master as of f68727292ae. best. -greg https://postgr.es/m/8s5lT8erXzBMugXJQ6Wginbp_gc2B4hmCYhF0Q0GpnuK87eCAOcKs5K31AWCwraCNFIQt42wwkow_MPPubHg485MWv-zDBY4NL_JX9yJEEg=@burd.me
v1-0001-Compute-the-distance-between-a-point-and-a-box-ex.patch
Description: Binary data
