I had an issue with a collision function returning very large values for distances
I would think python would not overflow a 16 bit integer when doing this math, since it’s dynamically typed, but apparently it does.
If I were to do these operations directly on an array, I understand why it would overflow, but here it is copying the value to another variable, x1, x2, ... , y3
, and then doing math on those to create distance
variables.
I would assume python would use 64 bit integers on those. But it doesn’t. They are still 16 bit.
I suspect, under the cover, its not really creating any new variables, just assigning them by reference.
Is this always the case, or does it only happen when using numpy arrays? This is one of the really frustrating things about python coming from being a c++ programmer.
def create_square(self, img):
color = self.random_color()
x = np.random.randint(0, img.shape[1] - square_size, dtype=np.uint16)
y = np.random.randint(0, img.shape[0] - square_size, dtype=np.uint16)
cv2.rectangle(img, (x, y), (x + square_size, y + square_size), color, -1)
return (x, y, square_size, color)
def collide(self, square1, square2, square3):
x1, y1, size1, _ = square1
x2, y2, size2, _ = square2
x3, y3, size3, _ = square3
# Calculate distances between squares
distance1 = (x1 - x2) ** 2 + (y1 - y2) ** 2
distance2 = (x1 - x3) ** 2 + (y1 - y3) ** 2
distance3 = (x2 - x3) ** 2 + (y2 - y3) ** 2
print("distance1",distance1)
print("distance2",distance2)
print("distance3",distance3)
# Check if all distances are below the threshold
if distance1 < (size1 + size2)**2 and distance2 < (size1 + size3)**2 and distance3 < (size2 + size3)**2:
return True
return False
def reset(self):
# Reset squares
self.squares = []
for _ in range(num_squares):
self.squares.append(self.create_square(np.zeros((600, 800, 3), dtype=np.uint16)))
Here is the output of distances
distance1 -18581859
distance2 -52348750
distance3 -46958403