Dan*_*ani 6 c++ algorithm computational-geometry
我有一个一维的网格.它的间距是一个浮点.我有一个浮点坐标点.我需要找到距离最近的网格点的距离.
例如:
0.12
|
*
|---------|---------|---------|---------|---------|
0 0.1 0.2 0.3 0.4 0.5
Run Code Online (Sandbox Code Playgroud)
结果将是-0.02因为最接近的点在它后面.
但如果是的话
-0.66
|
*
|---------|---------|---------|---------|---------|
-1 -0.8 -0.6 -0.4 -0.2 0
Run Code Online (Sandbox Code Playgroud)
结果将是0.06.正如你可以看到它的浮点,可能是负面的.
我尝试了以下方法:
float spacing = ...;
float point = ...;
while(point >= spacing) point -= spacing;
while(point < 0) point += spacing;
if(std::abs(point - spacing) < point) point -= spacing;
Run Code Online (Sandbox Code Playgroud)
它有效,但我确信有一种没有循环的方法
我们首先计算左右最近的点,如下所示:
leftBorder = spacing * floor(point/spacing);
rightBorder = leftBorder + spacing;
Run Code Online (Sandbox Code Playgroud)
然后距离很简单:
if ((point - leftBorder) < (rightBorder - point))
distance = leftBorder - point;
else
distance = rightBorder - point;
Run Code Online (Sandbox Code Playgroud)
请注意,我们可以通过天花板找到最近的点:
rightBorder = spacing * ceil(point/spacing);
leftBorder = rightBorder - spacing;
Run Code Online (Sandbox Code Playgroud)