Java 计算两点之间的距离

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/929773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:13:44  来源:igfitidea点击:

Calculating the distance between two points

java

提问by mrt181

I need to create a class which calculates the distance between two points. I am stuck and I am a total beginner. Here are my classes:

我需要创建一个计算两点之间距离的类。我被卡住了,我是一个完全的初学者。这是我的课程:

package org.totalbeginner.tutorial;

public class Point {

    public double x;
    public double y;

    Point(double xcoord, double ycoord){
        this.x = xcoord;
        this.y = ycoord;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }    
}

The second class.

第二课。

package org.totalbeginner.tutorial;

public class Line {

    double x;
    double y;

    Point p1 = new Point(2.0,2.0);
    Point p2 = new Point(4.0,4.0);
    Point mp = new Point(x,y);

    public void midpoint() {
        x = (p1.getX() + p2.getX()) / 2;
        y = (p1.getY() + p2.getY()) / 2;
    }
}

I am not sure how to get a point object (the middle point) between both defined points.

我不确定如何在两个定义的点之间获得一个点对象(中间点)。

I can create point objects but I am not sure how to return a point object through my midpoint()method that lies between those two point objects.

我可以创建点对象,但我不确定如何通过midpoint()位于这两个点对象之间的方法返回点对象。

采纳答案by paxdiablo

The distance between two points (x1,y1) and (x2,y2) on a flat surface is:

平面上两点 (x1,y1) 和 (x2,y2) 之间的距离为:

    ____________________
   /       2          2
 \/ (y2-y1)  + (x2-x1)

But, if all you want is the midpoint of your two points, you should change your midpoint function to:

但是,如果您想要的只是两点的中点,则应将中点函数更改为:

public Point midpoint (Point p1, Point p2) {
    return new Point ((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
}

This will return a brand new point object with the points set to the middle of the given two points (without having to concern yourself with any other math). And, since your second class is a line, you only need the two end points to describe it, so I'd make some minor changes.

这将返回一个全新的点对象,其点设置为给定的两个点的中间(无需关心任何其他数学)。而且,由于你的第二个类是一条线,你只需要两个端点来描述它,所以我会做一些小改动。

First Point.java:

第一Point.java

class Point {
    double x, y;
    Point (double xcoord, double ycoord) {
        this.x = xcoord;
        this.y = ycoord;
    }
    public double getX() { return x; }
    public double getY() { return y; }
}

Then Line.java:

然后Line.java

public class Line {
    Point p1, p2;
    Line (Point point1, Point point2) {
        this.p1 = point1;
        this.p2 = point2;
    }
    public Point midpoint() {
        return new Point ((p1.getX()+p2.getX())/2, (p1.getY()+p2.getY())/2);
    }
    public double abstand() {
        return Math.sqrt(
            (p1.getX() - p2.getX()) *  (p1.getX() - p2.getX()) + 
            (p1.getY() - p2.getY()) *  (p1.getY() - p2.getY())
        );
    }
    static public void main (String args[]) {
        Line s = new Line (new Point(2.0, 2.0), new Point(5.0, 6.0));
        Point mp = s.midpoint();
        System.out.println ("Midpoint = (" + mp.getX() + "," + mp.getY() + ")");
        double as = s.abstand();
        System.out.println ("Length   = " + as);
    }
}

These two files, when compiled and run with the endpoints 2,2and 5,6(the hypotenuse of a classic 3/4/5 right-angled triangle), generate the correct:

这两个文件,当编译并使用端点2,25,6(经典 3/4/5 直角三角形的斜边)运行时,生成正确的:

Midpoint = (3.5,4.0)
Length   = 5.0

回答by Oli

Simple Pythag... root(dx^2 + dy^2)

简单的勾股... root(dx^2 + dy^2)

Math.sqrt(Math.pow((p2.getX() - p1.getX()), 2) + Math.pow((p2.getY() - p1.getY()), 2))

回答by Johannes Schaub - litb

 X
 +
 |\
 | \
a|  \c
 |   \
 |    \
 +-----+ 
    b   Y

Imagine X and Y are your points on a flat surface. Then ais X.y - Y.yand bis Y.x - X.x. The length of cis their distance, and is the length of the hypotenuse of that triangle. It is calculated using

想象 X 和 Y 是您在平面上的点。然后aX.y - Y.y并且bY.x - X.x。的长度c是它们的距离,是那个三角形的斜边的长度。它是使用计算

sqrt(a^2 + b^2);

Since you see we are squaring aand b, the sign of them isn't relevant - it will come down to the same. So this method always works, where ever the points lie.

由于您看到我们正在平方ab,因此它们的符号无关紧要- 归结为相同。所以这个方法总是有效,无论点在哪里。

Lookup the Pythagorean theorem

查找 Pythagorean theorem

回答by eKek0

You can use the Pythagorean Theorem, as other said. Here is a visually demostration from the Wolfram Demostration Project.

正如其他人所说,您可以使用勾股定理。这是Wolfram 演示项目的视觉演示。

alt text http://demonstrations.wolfram.com/DistanceBetweenTwoPoints/HTMLImages/index.en/popup_5.jpg

替代文字 http://demonstrations.wolfram.com/DistanceBetweenTwoPoints/HTMLImages/index.en/popup_5.jpg

回答by JustJeff

Do you really need the distance, or are you trying to just get the midpoint? Because from your code snippet, it kind of looks like you just want to create a new point that is half-way between two existing points.

你真的需要距离,还是你只是想得到中点?因为从您的代码片段来看,您似乎只想创建一个位于两个现有点之间的新点。

If you're really just after the midpoint, you don't really need an entire 2nd class (i.e., 'Line') to accomplish that. Since the thing you are trying to find is also a point, it makes sense to add a constructor to your existing Point class, like so ..

如果你真的只是在中点之后,你真的不需要整个第二类(即“线”)来完成它。由于您试图找到的东西也是一个点,因此向现有 Point 类添加构造函数是有意义的,就像这样..

Point(Point a, Point b)
{
  x = (a.x + b.x) / 2;
  y = (a.y + b.y) / 2;
}

.. then, elsewhere let's say you already have a couple of points you want to use this on, you use the constructor thus:

.. 那么,在其他地方,假设您已经有几个要在其上使用它的点,因此您可以使用构造函数:

Point p1 = new Point(2,2);
Point p2 = new Point(4,4);
Point midpoint = new Point(p1, p2);

and if you really want distance between two points, that's not really an attribute of either point, so it makes sense to use a static method for that, like so

如果你真的想要两点之间的距离,那不是任何一点的真正属性,所以使用静态方法是有意义的,就像这样

public static double distance(Point a, Point b)
{
  double dx = a.x - b.x;
  double dy = a.y - b.y;
  return Math.sqrt(dx * dx + dy * dy);
}

and back in the calling code, you can use it this way:

回到调用代码,你可以这样使用它:

Point p1 = new Point(2,2);
Point p2 = new Point(4,4);
System.out.println("Distance between them is " + Point.distance(p1, p2));

回答by Paul Fisher

In your second class, it looks like you're trying to set the values of xand ythat are used to construct your mpvariable. All your formulas are correct, but you need to consider the orderthat everything is executed. In the code as it is, it's creating the xand yvariables, which start out as 0, then the various Points. xand yare still 0, so mpis set to Point(0, 0).

在您的第二堂课中,您似乎正在尝试设置用于构造变量的x和的值。你所有的公式都是正确的,但你需要考虑一切执行的顺序。在代码中,它创建了和变量,从 0 开始,然后是各种s。并且仍然为 0,所以设置为。ympxyPointxympPoint(0, 0)

What you probably want to do is change the return typeof midpointto Point, so that when you call that function, you get back a Point. Then you can create a new Pointobject with the values you calculate. It should look more like this:

你可能想要做的是改变返回值类型midpointPoint,所以,当你调用该函数,你回来一个Point。然后您可以Point使用您计算的值创建一个新对象。它应该看起来更像这样:

public Point midpoint() {
    // calculate the middle x and y
    double x = (p1.getX() + p2.getX()) / 2;
    double y = (p1.getY() + p2.getY()) / 2;
    // now make a new Point with those values, and return it
    return new Point(x, y);
}

回答by user2107534

You can use a Maths function for this:

您可以为此使用数学函数:

public Point midpoint() {
    //Calculate the difference between the old and new x/y
    double dx = p1.getX() - p2.getX();
    double dy = p1.getY() - p2.getY();

    double newX = Math.pow(dx, 2D);
    double newY = Math.pow(dz, 2D);
    return new Point(newX, newZ);
}

Math.powhandles the issues with negative values and etc. For you, using Math.pow gives you a safe method because it has a lot of checks built inside.

Math.pow处理负值等问题。对你来说,使用 Math.pow 给你一个安全的方法,因为它内置了很多检查。