0
votes

I try to get the distance between two points in http://processing.org/ is like java but dont works:

d = sqrt ((x2 - x1)**2 + (y2 - y1)**2);

the distance formula is: http://www.purplemath.com/modules/xyplane/dist07b.gif

6
Math.pow() is about 10x more expensive than using x * x. - Peter Lawrey

6 Answers

4
votes

Java doesn't have an exponentiation operator. Instead, try Math.pow(x, 2) or x*x.

3
votes

Processing already comes with a function to calculate the distance between two points in 2d and 3d. Just implement dist() as mentioned in the reference by handing over your x and y parameters of both points:

dist (x1, y1, x2, y2);
1
votes

You've got a couple of things a bit wrong. It should be:

d = sqrt ((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));

other options:

d = dist(x1,y1,x2,y2);

or

d = PVector.dist(new PVector(x1,y1),new PVector(x2,y2));

distance

Imagine you're distance as the hypothenuse of a right angled triangle. One side is defined by the X axis (it's length is x2-x1) and the other by the Y axis (it's length is y2-y1). Since the distance is the hypothenuse, and you know the sides, you simply apply Pythagoras theorem:

BC squared = AB squared + AC squared
BC = square root (AB squared + AC squared)
AC = (x2-x1) = dx
AB = (y2-y1) = dy
or
d = sqrt(dx*dx + dy*dy);
0
votes

According to http://processing.org/reference/ this should work:

d = sqrt ( pow ( x2 - x1, 2 ) + pow ( y2 - y1, 2 ) );

Although I'm not totally clear if you need this in Processing or in Java.

0
votes

Just use the built-in Processing classes and methods:

PVector x = new PVector(random(width), random(height));   
PVector y = new PVector(random(width), random(height));
System.out.println(getEuclidianDistance(x, y))