1.线性拟合获取指定数据对应的值
需求:已知温补表tempCompTable,想通过指定温度值temp,获取对应的温补值value
//打印温补表中的所有数据
for(auto& entry : tempCompTable)
{
printf("(%d, %d) \n", entry.first, entry.second);
}
//查找已知温度值temp对应的键值对iter
auto iter = tempCompTable.find(temp);
//temp在温补表中时,直接使用表中对应的“值”即可
if(iter != tempCompTable.end())
{
value = iter->second;
printf("TempCompTab have this temperature(%f),channel = %d, compvalue = %f db . %s() \n", temp, channel, value, __func__);
}
else//temp不在温补表中时,需要使用线性拟合计算temp对应的温补值
{
findClosestPoints(tempCompTable, temp);
int x1 = g_prevpoint->first;
int y1 = g_prevpoint->second;
int x2 = g_nextpoint->first;
int y2 = g_nextpoint->second;
value = y1 + (temp- x1) * (y2 - y1) / (x2 - x1);
printf("Caculate temperature compensation linear value,%s(), channel= %d, x1 = %d ,y1 = %d, x2 = %d, y2 = %d ,compvalue = %f db. \n", __func__ ,channel, x1, y1, x2, y2, value);
}
2.查找已知数据临近的数据
lower_bound 是 std::map 提供的一个成员函数,用于在 map 中查找第一个不小于 target_x 的元素。
std::map<int, int>::const_iterator g_prevpoint;
std::map<int, int>::const_iterator g_nextpoint;
void findClosestPoints(const std::map<int, int>& map_data, int target_x)
{
//查找第一个不小于target_x的元素
auto it = map_data.lower_bound(target_x);
g_prevpoint = it;
//只要it不是 map中的第一个,g_prevpoint-1就是小于target_x的第一个元素
if (g_prevpoint != map_data.begin())
{
g_prevpoint--;
}
//只要it不是map中的最后一个,it就是大于traget_x的第一个元素
if (it != map_data.end())
{
g_nextpoint = it;
}
}