【问题标题】:How to generate a line with exact number of points?如何生成具有精确点数的线?
【发布时间】:2019-05-12 10:22:19
【问题描述】:

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

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

我目前的幼稚方法并不精确,即它不会产生包含指定点数的路径(取决于数据集的密度和指定的目标长度,它偏离 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)。 我可以将生成的路径作为一个整体并插入整个数组,但我认为我首先正在寻找一种更智能的方式来生成路径。非常感谢任何帮助!

【问题讨论】:

  • Simplify.js 这样的库可能会有所帮助。
  • 不清楚,dataset[]应该怎么用?您可以在i/1024 生成积分
  • 不能轻易给出一个好的解决方案,因为你没有告诉我们你想要什么。你为什么这样做,即这条路是干什么用的?
  • 感谢您指出缺乏上下文和特异性。我试图简化问题以获得更好的说明,但我已更新问题以希望使其更清晰。

标签: javascript arrays algorithm interpolation linear-interpolation


【解决方案1】:

看起来你想要的就是这样:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2012-03-27
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    相关资源
    最近更新 更多