Rotating and scaling vectors are common operations in computer graphics and machine learning applications. Python provides a rich library of tools for performing such operations. In this article, we will explore how to rotate and scale a vector in Python.
A vector in two-dimensional space can be represented by a tuple or list of two numbers. The first number represents the horizontal component, and the second represents the vector’s vertical component. We can rotate a vector by a certain angle using the following formula:
import mathdef rotate_vector(vector, angle):x = vector[0] * math.cos(angle) - vector[1] * math.sin(angle)y = vector[0] * math.sin(angle) + vector[1] * math.cos(angle)return [x, y]
Here, vector
is the vector to be rotated, and angle
is the angle (in radians) we want to rotate the vector. The math.cos
and math.sin
functions are used to compute the cosine and sine of the angle, respectively. The rotated vector is returned as a list of two numbers.
We can scale a vector by multiplying its horizontal and vertical components by a scaling factor. This can be achieved using the following code:
def scale_vector(vector, scale):x = vector[0] * scaley = vector[1] * scalereturn [x, y]
Here, vector
is the vector to be scaled, and scale
is the scaling factor. The scaled vector is returned as a list of two numbers.
We can combine rotation and scaling operations to achieve more complex transformations. For example, suppose we want to rotate a vector by an angle of 45 degrees and then scale it by a factor of 2. We can achieve this using the following code:
vector = [1, 1]angle = math.radians(45)scale = 2# Rotate the vectorvector = rotate_vector(vector, angle)# Scale the vectorvector = scale_vector(vector, scale)print(vector) # Output: [1.414213562373095, 1.414213562373095]
Here, we first define the vector to be transformed (vector
), the angle by which we want to rotate the vector (angle
), and the scaling factor (scale
). We then rotate the vector using the rotate_vector
function, and scale the resulting vector using the scale_vector
function. The final transformed vector is printed to the console.
In this article, we have explored how to rotate and scale a vector in Python. These operations are useful in various applications, including computer graphics, machine learning, and physics simulations. Using the code snippets provided in this article, you can easily incorporate these operations into your Python projects.
Quick Links
Legal Stuff
Social Media