如何生成精确点数的线?

时间:2019-05-12 10:22:19

标签: javascript arrays algorithm interpolation linear-interpolation

我必须从n个点的数据集中生成路径。 我正在通过此数据集中的点绘制三次样条。 生成的路径必须包含确切数量的投影路径点。

我的问题不在于曲线的绘制,而是路径点沿x轴的分布以产生由精确数字组成的路径这就是为什么我将以下示例简化为一维点阵列,应通过这些点绘制一条直线。数据集中的每个点都应代表曲线段的起点(尽管由于简化,曲线实际上是一条线)。

我目前的幼稚方法并不精确,即它不会产生包含指定点数的路径(根据数据集的密度和指定的targetLength的不同,它会减少4-5个点)。

我认为我必须使用线性插值才能获得准确的结果,但我不知道如何。谁能帮助我或指出正确的方向?

天真的方法(javascript):

// Array with floating point values constrained between 0 - 1
// Think of each value as the beginning of a line segment.
const dataset = [0, 0.123, 0.3432, 0.454, 0.56, 0.8334, 0.987, 1];

// Path should have this many points
const targetLength = 1024;

// Step distance between points
const delta = 1 / targetLength;

// The path array we're generating
const path = [];

// For each point (segment)
for (let i = 0; i < dataset.length - 1; i++) {

  const x1 = dataset[i]; // current point
  const x2 = dataset[i + 1]; // next point
  const xd = x2 - x1 - delta; // dist between current and next point(-delta)

  // For each step in the segment generate a path-point
  for (let k = 0; k <= xd; k += delta) {
    // For this example we're only pushing the x-value onto the array.
    // In the real implementation I'm calculating a y-value to plot a curve
    // and push an array of [x, y] onto the dataset.
    path.push(dataset[i] + k);
  }

}

// expect: path.length === targetLength
console.log(path.length);

在上面的示例中,我希望path.length等于targetLength(1024)。 我可以将生成的路径作为一个整体,然后对整个数组进行插值,但是我认为我正在寻找一种更智能的生成路径的方法。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您真正想要的就是这样:

for (let i=0; i<targetLength; ++i) {
    path.push(i / (targetLength-1));
}

...,因为这是您近似的值,对于某些三次样条插值实际上很有意义。但是,您通常不需要存储这些路径点,因为它们很容易计算。