X1 - X2 always positive

Cags

Contributor
Joined
Feb 19, 2004
Messages
695
Location
Melton Mowbray, England
I'm trying to work out the distance between 2 points which is obviously done by doing X1 - X2. As the points can be either way around and I need a positive number i'm currently using an if statement to find out which is biggest. Then taking the smallest from the largest. Is there an easier way of ensuring the number is positive. Mathematically speaking I could just square then square root the number, but this doesn't seem any more elegant than an if statement.

My current code...

C#:
	if(e.X > pSelStart.X)
		iWidth = e.X - pSelStart.X;
	else
		iWidth = pSelStart.X - e.X;
 
For the distance between two points you will square the x and y differences - which means it wont matter if there are negatives.

dx = x1 - x2
dy = y1 - y2
distance = squareroot (dx*dx + dy*dy)
 
Cags said:
I realised this as I said in my post, but PlausiblyDamps solution is far more elegant.

The two solutions are not equal.

The solution of PlausiblyDamp works great for 2 points on a straight line, but stops working when you're working with x and y coordinates.
If you're using 2d coordinates (x and y) you have to use the x^2 + y^2 = z^2 rule. The result will be (a lot) different from abs(x difference) + abs(y difference).
 
Yes that would give a differen't result, but I have no intention of doing that. As the title stated I was trying to find the distance between 2 X co-ordinates not the difference between 2 points. The reason I'm doing this is because I'm creating a drag select for a program thus needing a rect object of the selected area (similar to the one in explorer). Todo this I need to work out how far the pointer has travelled in either dimension not in total. Otherwise I would have done as you suggested and applied pythagoras's theorum. :)

Thus given

C#:
Point pStart;
Point pCurrent;

the rectangle will be

C#:
width = Math.Abs(pStart.X - pCurrent.X)
height = Math.Abs(pStart.Y - pCurrent.Y)
x = Math.Min(pStart.X, pCurrent.X) 
y = Math.Min(pStart.Y, pStart.Y)

Rectangle rectSelection = new Rectangle(x, y, width, height);

This method is far neater than the original rough method I was using to test selection which involved a couple of if else statements.
 
"I'm trying to work out the distance between 2 points which is obviously..."

hence the misunderstanding :-\
 
Back
Top