2D Vector

Overview

A 2D vector is a fundamental concept in mathematics and computer science, particularly in fields like graphics programming and data science. It can be represented as a tuple with two elements, such as ((x, y)). In matrix terms, a 2D column vector is a (2 \times 1) matrix, while a 2D row vector is a (1 \times 2) matrix. This representation allows for various mathematical operations and transformations that are essential in computational tasks.

Representation and Operations

In programming, a 2D vector can be encapsulated in a class, such as the Vec2 class. This class provides a structured way to perform vector operations like addition, scalar multiplication, and equality testing. The Vec2 class uses operator overloading to allow the use of + and * operators for vector arithmetic, making the code more intuitive and readable. Additionally, it provides a custom string representation for easy reading and debugging.

Vec2 Class Implementation

Below is the implementation of the Vec2 class, which demonstrates how a 2D vector can be represented and manipulated in code:

class Vec2():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def add(self, v2):
        return Vec2(self.x + v2.x, self.y + v2.y)

    def scale(self, scalar):
        return Vec2(scalar * self.x, scalar * self.y)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __add__(self, v2):
        return self.add(v2)

    def __mul__(self, scalar):
        return self.scale(scalar)

    def __rmul__(self, scalar):
        return self.scale(scalar)

    def __repr__(self):
        return "Vec2({}, {})".format(self.x, self.y)

Key Features of the Vec2 Class

  • Initialization: The constructor __init__ initializes the vector with two components, x and y.
  • Addition: The add method and the overloaded __add__ operator allow for the addition of two vectors.
  • Scalar Multiplication: The scale method and the overloaded __mul__ and __rmul__ operators enable multiplication of the vector by a scalar.
  • Equality Testing: The __eq__ method checks if two vectors are equal by comparing their respective components.
  • String Representation: The __repr__ method provides a readable string representation of the vector, useful for debugging and display purposes.

This class structure not only encapsulates the data but also provides a clear interface for performing common vector operations, making it a powerful tool for programmers and data scientists working with 2D vectors.

FAQ (Frequently asked questions)

What class is used to represent a 2D vector?

Does the Vec2 class provide a custom string representation?

How does the Vec2 class check for vector equality?