是否有一种简单、有效的方法可以在 C# 中实现分段线性整数到整数曲线插值(对于 Unity3D,如果重要的话)?
详情如下:
- 分段线性曲线表示必须随着时间的推移而构建。第一个插值请求出现在我们拥有所有数据点之前
- 曲线是严格单调的
- 第一个点总是 (0, 0)
- 数据点的第一个坐标也是严格单调的到达时间,即点按它们的第一个坐标自然排序。
- 数据点不在会导致 4 字节整数溢出问题的范围内
- 输出不必是 100% 准确,因此舍入误差不是问题。
在 C++ 中,我会做这样的事情:
#include <algorithm>
#include <vector>
#include <cassert>
using namespace std;
typedef pair<int, int> tDataPoint;
typedef vector<tDataPoint> tPLC;
void appendData(tPLC& curve, const tDataPoint& point) {
assert(curve.empty() || curve.back().first < point.first);
curve.push_back(point);
}
int interpolate(const tPLC& curve, int cursor) {
assert(!curve.empty());
int result = 0;
// below zero, the value is a constant 0
if (cursor > 0) {
// find the first data point above the cursor
const auto upper = upper_bound(begin(curve), end(curve), cursor);
// above the last data point, the value is a constant 0
if (upper == end(curve)) {
result = curve.back().second;
} else {
// get the point below or equal to the cursor
const auto lower = upper - 1;
// lerp between
float linear = float((cursor - lower.first) * (upper.second - lower.second)) / (upper.first - lower.first);
result = lower.second + int(linear);
}
}
return result;
}
我可以看到我如何在 C# 中做一些类似这样的工作,但没有什么简洁或高效的。任何帮助将不胜感激。
编辑:我不需要更准确,并且对分段线性插值非常满意,因此更好的插值质量不是我的问题。
我正在寻找的是一种高效、简洁的方法。高效,我的意思是:依靠数据点自然排序的事实,以便能够使用二进制搜索来找到正确的段