我有一个一维网格。它的间距是一个浮点数。我也有一个带浮点坐标的点。我需要找出它到最近网格点的距离。
例如:
0.12
|
*
|---------|---------|---------|---------|---------|
0 0.1 0.2 0.3 0.4 0.5结果将是-0.02,因为最近的点在它的后面。
但是,如果是
-0.66
|
*
|---------|---------|---------|---------|---------|
-1 -0.8 -0.6 -0.4 -0.2 0结果将是0.06。你可以看到它是浮点数,也可以是负数。
我尝试了以下几种方法:
float spacing = ...;
float point = ...;
while(point >= spacing) point -= spacing;
while(point < 0) point += spacing;
if(std::abs(point - spacing) < point) point -= spacing;它是有效的,但我相信有一种不需要循环的方法
发布于 2011-12-02 03:15:27
让我们首先计算左边和右边最近的点,如下所示:
leftBorder = spacing * floor(point/spacing);
rightBorder = leftBorder + spacing;那么距离就很简单了:
if ((point - leftBorder) < (rightBorder - point))
distance = leftBorder - point;
else
distance = rightBorder - point;请注意,我们可以通过天花板找到最近的点:
rightBorder = spacing * ceil(point/spacing);
leftBorder = rightBorder - spacing;发布于 2011-12-02 02:51:27
std::vector<float> spacing = ...;
float point = ...;
float result;既然你说间距不是(线性的),我将缓存总和:
std::vector<float> sums(1, 0.0);
float sum=0;
for(int i=0; i<spacing.size(); ++i)
sums.push_back(sum+=spacing[i]);
//This only needs doing once.
//sums needs to be in increasing order. 然后执行二进制搜索以找到左侧的点:
std::vector<float>::iterator iter;
iter = std::lower_bound(sums.begin(), sums.end(), point);然后从那里找到结果:
if (iter+1 == sums.end())
return point-*iter;
else {
float midpoint = (*iter + *(iter+1))/2;
if (point < midpoint)
result = point - *iter;
else
result = *(iter+1) - point;
}编辑:别让我觉得自己很傻。你说过间距不是恒定的。我将其解释为非线性。但是,您的示例代码是线性的,只是不是编译时常量。是我的错。我将把这个答案作为一个更一般的解决方案,尽管你的(线性)问题可以更快地解决。
发布于 2011-12-02 02:57:01
这是我第一次尝试刷脸,请注意,这根本没有经过测试。
float remainder = fmod(point, spacing); // This is the fractional difference of the spaces
int num_spaces = point/spacing; // This is the number of "spaces" down you are, rounded down
// If our fractional part is greater than half of the space length, increase the number of spaces.
// Not sure what you want to do when the point is equidistant to both grid points
if(remainder > .5 * spacing)
{
++num_spaces;
}
float closest_value = num_spaces*spacing;
float distance = closest_value - point;https://stackoverflow.com/questions/8346452
复制相似问题