Calculating the distance between two X, Y coordinates in PHP

I am writing a game tool that involves calculating the distance between two coordinates on a toroidal plane 500 units across. That is, [0,0] by [499,499] are real coordinates, and [0,0] and [499,499] are also next to each other.

Currently, in my application, I am comparing the distance between the city with the location [X, Y] corresponding to the user's own location [X, Y], which they previously configured.

To do this, I found this algorithm, which works:

Math.sqrt ( dx * dx + dy * dy );

Since sorting a computed list by distance is a useful thing I can do, I applied this algorithm in a MySQL query and made it available for my application using the following part of the SELECT statement:

SQRT( POW( ( ".strval($sourceX)." - cityX ) , 2 ) + POW( ( ".strval($sourceY)." - cityY ) , 2 ) ) AS distance

This is great for many calculations, but does not take into account the fact that [0,0] and [499,499] the kitten is angle to each other.

Is there any way to tune this algorithm to create an exact distance, given that 0 and 499 are adjacent?

+3
source share
7 answers

Update (torus):

Well, from your own comments, it seems that you mean the torus - the surface of the donut - and not the sphere. ( This is a big difference, and you have to edit your question : to call it a sphere wrong .)

- , , . , , - 250 = 500/2 0 250.

, - - ( PHP, )

dx1 = min(dx, 500-dx)
dy1 = min(dy, 500-dy);
distance = Math.sqrt(dx1*dx1 + dy1*dy1);

( , dx dy .)

, .

():

, (x, y) !

() , , , , , .

(x, y) , , (.. haversine), 0- > 499 0- > 360 -90- > 90 . (, lon lat - !)

, , , , , (x, y) , .

(, , , , , , , , , !)

+5

, . , .

, 500x500 x ( y) 250. ( 250 , 500-x .)

dx = Math.abs(dx);
dy = Math.abs(dy);
if (dx > 250)
  dx = 500 - dx;
if (dy > 250)
  dy = 500 - dy;
distance = Math.sqrt ( dx * dx + dy * dy );
+7

, , "". . (x, y) (x + * w, y + j * h) j w h - "" .

, , - (d (p1, p2))) i, j.

, = -1,0,1 j = -1,0,1, .

+1

, SELECT:

SQRT( POW( LEAST( ABS($sourceXstr-cityX), ( 500 +LEAST($sourceXstr,cityX)-GREATEST($sourceXstr,cityX))) , 2 ) + POW( LEAST( ABS($sourceYstr-cityY), ( 500 +LEAST($sourceYstr,cityY)-GREATEST($sourceYstr,cityY))) , 2 ) ) AS distance

0

, , , . - .

If your points are in a two-dimensional plane, the distance between the points (x1, y1) and (x2, y2) is determined by the Pythagorean theorem :

Pythagorean formula

d = squareroot( square(x2 - x1) + square(y2 - y1) )

In PHP,

$x1 = $y1 = 2;
$x2 = $y2 = 5;
$distance = sqrt( pow(($x2-$x1),2) + pow(($y2-$y1),2) );
echo $distance;              // 4.2426406871193
0
source

Source: https://habr.com/ru/post/1783081/


All Articles