OK, so I\'ve written most of a program that will allow me to determine if two circles overlap.
I have no problems whatsoever with my program aside from one issue: t
Math.sqrt returns a double so you'll have to cast it to int as well
distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
You could also you Point2D Java API class:
public static double distance(double x1, double y1, double x2, double y2)
Example:
double distance = Point2D.distance(3.0, 4.0, 5.0, 6.0);
System.out.println("The distance between the points is " + distance);
This may be OLD, but here is the best answer:
float dist = (float) Math.sqrt(
Math.pow(x1 - x2, 2) +
Math.pow(y1 - y2, 2) );
Based on the @trashgod's comment, this is the simpliest way to calculate distance:
double distance = Math.hypot(x1-x2, y1-y2);
From documentation of Math.hypot
:
Returns:
sqrt(x²+ y²)
without intermediate overflow or underflow.
Unlike maths-on-paper
notation, most programming languages (Java included) need a *
sign to do multiplication. Your distance calculation should therefore read:
distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
Or alternatively:
distance = Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));
Based on the @trashgod's comment, this is the simpliest way to calculate >distance:
double distance = Math.hypot(x1-x2, y1-y2);
From documentation of Math.hypot:Returns:
sqrt(x²+ y²)
without intermediate overflow or underflow.Bob
Below Bob's approved comment he said he couldn't explain what the
Math.hypot(x1-x2, y1-y2);
did. To explain a triangle has three sides. With two points you can find the length of those points based on the x,y
of each. Xa=0, Ya=0
If thinking in Cartesian coordinates that is (0,0)
and then Xb=5, Yb=9
Again, cartesian coordinates is (5,9)
. So if you were to plot those on a grid, the distance from from x to another x assuming they are on the same y axis is +5
. and the distance along the Y axis from one to another assuming they are on the same x-axis is +9
. (think number line) Thus one side of the triangle's length is 5, another side is 9. A hypotenuse is
(x^2) + (y^2) = Hypotenuse^2
which is the length of the remaining side of a triangle. Thus being quite the same as a standard distance formula where
Sqrt of (x1-x2)^2 + (y1-y2)^2 = distance
because if you do away with the sqrt on the lefthand side of the operation and instead make distance^2 then you still have to get the sqrt from the distance. So the distance formula is the Pythagorean theorem but in a way that teachers can call it something different to confuse people.