Write a pyhton function to calculate distance between two 3d vectors, include some tests
- User
Write a pyhton function to calculate distance between two 3d vectors, include some tests
Assistant
Sure! Here is a Python function to calculate the distance between two 3D vectors, along with some test cases:
import unittest def distance_3d(v1, v2): """ Calculate the distance between two 3D vectors. Args: v1 (list): The first 3D vector. v2 (list): The second 3D vector. Returns: float: The distance between the two vectors. """ return np.linalg.norm(v1 - v2) class TestDistance3d(unittest.TestCase): def test_distance_3d(self): # Test with two vectors in the same direction v1 = [1, 0, 0] v2 = [2, 0, 0] self.assertAlmostEqual(distance_3d(v1, v2), 1.4142135623730666) # Test with two vectors in opposite directions v1 = [1, 0, 0] v2 = [-1, 0, 0] self.assertAlmostEqual(distance_3d(v1, v2), 2.828427124746618) # Test with two vectors at the same position v1 = [0, 0, 0] v2 = [0, 0, 0] self.assertAlmostEqual(distance_3d(v1, v2), 0) # Test with a vector and a scalar v1 = [1, 0, 0] v2 = 2 self.assertAlmostEqual(distance_3d(v1, v2), 1.4142135623730666) if __name__ == '__main__': unittest.main()Here's an explanation of the different test cases:
test_distance_3d: This test checks that the distance between two vectors in the same direction is correct. In this case, the vectors are both in the x-direction, so the distance should be the magnitude of the vector.test_distance_3d: This test checks that the distance between two vectors in opposite directions is correct. In this case, the vectors are both in the x-direction, but one is negative, so the distance should be the magnitude of the vector multiplied by the sine of the angle between the vectors.test_distance_3d: This test checks that the distance between two vectors at the same position is zero.test_distance_3d: This test checks that the distance between a vector and a scalar is correct. In this case, the scalar is 2, so the distance should be the magnitude of the vector.
You can run the tests by executing the file or by using a test runner like pytest.
Note that this implementation uses NumPy's
linalg.normfunction to calculate the distance between the vectors. This function returns the Euclidean distance between the two vectors, which is the distance we are looking for in this case.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.