【问题标题】:Generate 8 coordinates between a start coordinate and end coordinate在起始坐标和结束坐标之间生成 8 个坐标
【发布时间】:2017-11-26 20:41:48
【问题描述】:

嗯,我有两个坐标(红色圆圈)

我想生成所有这些果岭。我知道我走错了

我正在使用以下代码

import java.util.ArrayList;
import java.util.List;

public class classA {

    static final int startX = 52760;
    static final int startY = 72440;
    static final int endX = 52520;
    static final int endY = 71896;
    static final List<String> coordinates = new ArrayList<>();

    public static void main(String[] args) 
    {

        calculate(startX, startY, endX, endY);

        coordinates.forEach(System.out::println);
    }

    private static void calculate(int _startX, int _startY, int _endX, int _endY) 
    {

        final int _x = (_startX + _endX) / 2;
        final int _y = (_startY + _endY) / 2;

        coordinates.add(_x + "," + _y);

        if (coordinates.size() != 8)
            calculate(startX, startY, _x, _y);
    }
}

我可以理解代码将从“下一个”结束值(即中心)计算开始值,但我无法配置它

输出是

我应该怎么做?谢谢!

【问题讨论】:

  • 为什么每次都除以2? (或者事实上,为什么这里完全涉及 2?)
  • 这更像是一个数学问题,而不是除以 2,您应该计算这 2 个点之间的距离,然后将点放在该距离的 1/8 上,然后放在距离的 2/8 上,等等.
  • 为什么涉及递归?这可以通过每次增加开始和结束之间距离的 1/9 的循环来轻松完成。 (为什么是 1/9 而不是 1/8?谷歌一错再错)
  • @FilipRistic 考虑到以下代码是正确的,这种情况下的距离是 594 (int) Math.sqrt((endX - startX) * (endX - startX) + (endY - startY) * (endY - startY)) 但是我怎样才能得到这个 594 的 1/8 的坐标呢?

标签: java coordinates


【解决方案1】:

说明

在每一步中,您实际上是将距离分成两半:

final int _x = (_startX + _endX) / 2;
final int _y = (_startY + _endY) / 2;

这也是为什么你在(start, middle)的中间看到第一个点,然后在中间看到下一个点的确切原因。


解决方案

你想要达到的目标叫做linear interpolation

您需要将距离分成大小相等的(8 + 1) = 9 部分(中间8 部分,共9 个点)。您可以使用

(end - start) / 9

之后,您反复将其添加到start 并获得所有积分。或者(为了更精确)使用乘法

start + i * ((end - start) / 9)

接收i-th 新点。

此外,您不应使用 整数除法,因为它总是向下舍入。要获得精确的结果,您应该转换为 double,然后计算结果,最后转换回 int 以显示值。


代码

代码如下:

private static void calculate(int startX, int startY, int endX, int endY) {
    int amount = 8;

    // Compute the distance to each point
    double wholeDistanceX = endX - startX;
    double distanceX = wholeDistanceX / (amount + 1);

    double wholeDistanceY = endY - startY;
    double distanceY = wholeDistanceY / (amount + 1);

    // Add all new points
    for (int i = 1; i <= amount; i++) {
        // Compute current point
        double currentX = startX + i * distanceX;
        double currentY = startY + i * distanceY;

        // Create the point
        coordinates.add((int) currentX + "," + (int) currentY);
    }
}

请注意,在 Java 中,您通常不会在变量前面使用 _


插图

这是我刚刚画的一张快速图片,应该有助于理解方程式:

您会看到第一个和最后一个点位于startend。距离为end - start。距离除以9 与第一个点到第二个点的距离一样长。因此第六点位于

start + 6 * ((end - start) / 9)

【讨论】:

  • 作为一个小改进 - 使用乘法而不是增量加法。后者可能会导致累积精度问题。
  • 谢谢@OliverCharlesworth!我现在完全明白它是如何工作的了!它工作完美:)
猜你喜欢
  • 2019-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多