Calculate distance between two x/y coordinates?

前端 未结 4 1143
面向向阳花
面向向阳花 2021-02-05 05:18

I would like to calculate the distance between two x/y coordinates on the surface of a torus. So, this is a normal grid that has the property that its corners and sides are \'co

4条回答
  •  心在旅途
    2021-02-05 06:08

    If your grid wraps around at the edges, there will be four distances between each coordinate (for 2 dimensions). I'm assuming you want to know the shortest distance.

    Let's use a smaller grid, the numbers are a bit more manageable. Say the grid is 10x10. Let's also use just one dimension for simplicity (in which case there'll be just two distances), just as you have in your example. Say we have the points 0,2 and 0,6. The two distances between the points are d_1 = (6-2) = 4 and d_2 = (10-6) + 2 = 6, so in this case the shortest distance would be d_1.

    In general, you can do the following:

    • For each coordinate:
      • subtract the smaller from the larger number
      • if the result is greater than half the width of the grid the shortest distance in this coordinate is the grid width minus the result
      • if the result is less than half the width of the grid, the shortest distance in this coordinate is the result

    Then using Pythagoras' theorem, the shortest distance between the two points is the square root of the sum of the squares of the shortest distances in each direction. You can calculate the other three distances by calculating Pythagoras' theorem using the other combinations of distances in each direction.

    As another poster has said, the shape formed when you wrap round at the edges (for a 2 dimensional grid) is a torus and I think the method I've used above is the same as the equation given but has the advantage that it can be extended to n-dimensions if required. Unfortunately there's not really an easy visualisation above 2 dimensions.

提交回复
热议问题