获取网格上最接近的点
Getting closest point on grid to point
我有一个一维网格。它的间距是一个浮点。我也有一个浮点坐标的点。我需要找到它到最近网格点的距离
例如:
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;
它是有效的,但我相信有一种方法没有循环
让我们首先计算左侧和右侧最近的点,如下所示:
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;
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;
}
别觉得我傻了。你说间距不是恒定的。我认为这不是线性的。但是,您的示例代码是线性的,只是不是编译时常数。我的坏。我将把这个答案作为一个更通用的解决方案,尽管你的(线性(问题可以更快地解决。
这是我的第一次脸红尝试,请注意,这根本没有经过测试。
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;
您应该使用以下方法对数字进行四舍五入:
float spacing = ...;
float point = ...;
(point > 0.0) ? floor(point + spacing/2) : ceil(point - spacing/2);
更普遍地说,对于任意的间距、尺寸和距离度量(公制(,您要寻找的结构将是Voronoi图。
相关文章:
- 查找最接近的大于当前数字的数字的索引
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 查找索引的最接近的真实值
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- C++ lower_bound() 搜索最接近目标值的元素
- C++有效地找到向量中第一个最接近的匹配值?
- 在结构向量中查找最接近的值
- 在排序数组中搜索最接近的 int 值 <= 从右起给定值
- 最接近"std::atomic<std::vector>"是什么?
- C++中最接近 Lua 表操作的东西是什么?
- 在std::集中获取与给定元素最接近的元素
- 查找整数数组中最接近的数字
- Systemc - 将sc_time四舍五入到最接近的第 10 SC_NS
- 我是 c++ 的新手,有没有一种算法可以找到 3d 数组中最接近的 0 的距离?
- 我的程序不断四舍五入到最接近的整数
- 3 与错误最接近的总和:字符串常量之前的预期非限定 id
- 最接近Direct2D/DirectWrite的跨平台替代方案?
- 从源开始,在C++中找到网格上最接近目标的下一个点
- 从均匀网格中查找最接近的数字
- 获取网格上最接近的点