Vector Magnitude

The magnitude of a vector from A to B is the distance between those two points. Continuing with the cyber-soldier theme, Alpha has a limited amount of fuel and needs to calculate the distance from A to B to know if he can make it to B. We have already calculated vector AB as (20, 15). The magnitude will give us the distance he needs to travel.

To calculate the magnitude of a vector, square the components, add them together, and then take the square root of the result. So the magnitude of a vector (20, 15) is the square root of 20 x20 + 15 x15, which is 25 (see Figure 5-2). Let's add a method to our Vector2 to calculate the magnitude (Listing 5-8).

Figure 5-2. Creating a vector

Listing 5-8. Vector Magnitude Function import math class Vector2(object):

@classmethod def from_points(cls, P1, P2):

def get_magnitude(self):

A = (10.0, 20.0) B = (30.0, 35.0) AB = Vector2.from_points(A, B) print AB

print AB.get_magnitude()


Figure 5-2. Creating a vector




point A

The line math.sqrt(self.x**2 + self.y**2) does the magnitude calculation. The ** operator in Python raises a value to a power, so we could just as easily have written the calculation as math.sqrt(self.x*self.x + self.y*self.y).

The last few lines create a test vector, and then call the get_magnitude we just added. If you have some graph paper handy, you may want to plot the points A and B and verify that the distance between the two is 25.0.

Was this article helpful?

0 0

Post a comment