Tutorial :Calculating the distance between two points


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 Punkt {        public double x;      public double y;        Punkt(double xkoord, double ykoord){          this.x = xkoord;          this.y = ykoord;      }        public double getX() {          return x;      }        public double getY() {          return y;      }      }  

The second class.

package org.totalbeginner.tutorial;  public class Strecke{        double x;      double y;        Punkt p1 = new Punkt(2.0,2.0);      Punkt p2 = new Punkt(4.0,4.0);      Punkt mp = new Punkt(x,y);        public void mittelpunkt(){          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 mittelpunkt() method that lies between those two point objects.


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

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

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

public Punkt mittelpunkt (Punkt p1, Punkt p2) {      return new Punkt ((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 Punkt.java (Point):

class Punkt {      double x, y;      Punkt (double xkoord, double ykoord) {          this.x = xkoord;          this.y = ykoord;      }      public double getX() {          return x;      }      public double getY() {          return y;      }  }  

Then Strecke.java (Line):

public class Strecke {      Punkt p1, p2;      Strecke (Punkt punkt1, Punkt punkt2) {          this.p1 = punkt1;          this.p2 = punkt2;      }      public Punkt mittelPunkt() {          return new Punkt ((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[]) {          Strecke s = new Strecke (new Punkt(2.0, 2.0), new Punkt(5.0, 6.0));          Punkt mp = s.mittelPunkt();          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,2 and 5,6 (the hypotenuse of a classic 3/4/5 right-angled triangle), generate the correct:

Midpoint = (3.5,4.0)  Length   = 5.0  


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

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


A lazy programmer solution using the java2D point API


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

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

sqrt(a^2 + b^2);  

Since you see we are squaring a and 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.

Lookup the Pythagorean theorem


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., 'Strecke') 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 ..

Punkt(Punkt a, Punkt 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:

Punkt p1 = new Punkt(2,2);  Punkt p2 = new Punkt(4,4);  Punkt midpoint = new Punkt(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(Punkt a, Punkt 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:

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


You can use a Maths function for this:

public Punkt mittelpunkt() {      //Calculate the difference betwen 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 Punkt(newX, newZ);  }  

handles the issues with negative values and etc. for you.
using Math.pow gives you a safe method because it has alot of checks builded inside


They teach Pythagoras' theorem in early high school here. There is a good chance that anything you learnt in maths will be useful in computer science at some point.


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

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


In your second class, it looks like you're trying to set the values of x and y that are used to construct your mp variable. All your formulas are correct, but you need to consider the order that everything is executed. In the code as it is, it's creating the x and y variables, which start out as 0, then the various Punkts. x and y are still 0, so mp is set to Punkt(0, 0).

What you probably want to do is change the return type of mittelpunkt to Punkt, so that when you call that function, you get back a Punkt. Then you can create a new Punkt object with the values you calculate. It should look more like this:

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »