diff --git a/mesa/space.py b/mesa/space.py index 2db3f1db5e7..528df09563d 100644 --- a/mesa/space.py +++ b/mesa/space.py @@ -572,12 +572,15 @@ def get_distance(self, pos_1, pos_2): pos_1, pos_2: Coordinate tuples for both points. """ - pos_1 = np.array(pos_1) - pos_2 = np.array(pos_2) + x1, y1 = pos_1 + x2, y2 = pos_2 + + dx = np.abs(x1 - x2) + dy = np.abs(y1 - y2) if self.torus: - pos_1 = (pos_1 - self.center) % self.size - pos_2 = (pos_2 - self.center) % self.size - return np.linalg.norm(pos_1 - pos_2) + dx = min(dx, self.width - dx) + dy = min(dy, self.height - dy) + return np.sqrt(dx * dx + dy * dy) def torus_adj(self, pos): """ Adjust coordinates to handle torus looping. diff --git a/tests/test_space.py b/tests/test_space.py index 8f53b33d539..8bf4064e46b 100644 --- a/tests/test_space.py +++ b/tests/test_space.py @@ -1,6 +1,7 @@ import unittest import networkx as nx +import numpy as np from mesa.space import ContinuousSpace from mesa.space import SingleGrid @@ -49,6 +50,14 @@ def test_distance_calculations(self): pos_3 = (-30, -20) assert self.space.get_distance(pos_1, pos_3) == 10 + pos_4 = (20, -5) + pos_5 = (20, -15) + assert self.space.get_distance(pos_4, pos_5) == 10 + + pos_6 = (-30, -29) + pos_7 = (21, -5) + assert self.space.get_distance(pos_6, pos_7) == np.sqrt(49 ** 2 + 24 ** 2) + def test_heading(self): pos_1 = (-30, -30) pos_2 = (70, 20)