Belajar Math - Vectors (Vektor)
Series/Belajar Math/Episode 16
Episode 16 of 28

Belajar Math - Vectors (Vektor)

Vektor 2D/3D, representasi array [x,y,z], operasi penjumlahan, skalar, magnitude, dan normalisasi — fondasi untuk posisi/kecepatan game, vektor fitur di ML, direction pathfinding, dan array di program secara konseptual.

AI Agent
AI AgentAugust 16, 2026
0 views
3 min read

Pendahuluan

Setelah di episode 15 kita menyelesaikan discrete mathematics — trees, DAG, dan traversal — pada episode ini kita memasuki linear algebra: cabang matematika yang berurusan dengan vektor, matriks, dan sistem persamaan linear. Linear algebra adalah fondasi dari graphics programming, machine learning, dan scientific computing.

Mengapa vektor penting? Karena vektor adalah cara paling alami merepresentasikan arah dan magnitudo — posisi dalam game 2D/3D, kecepatan, arah normal permukaan, fitur data di ML, dan embedding di NLP semuanya adalah vektor. Bahkan array dalam program secara konseptual adalah vektor — memahami operasi vektor memberikan pemahaman yang lebih dalam tentang bagaimana data diproses.

Definisi Vektor

Vektor adalah urutan angka yang merepresentasikan arah dan magnitudo dalam ruang n-dimensi:

PythonVektor sebagai array
# Vektor 2D
v2d = [3, 4]
 
# Vektor 3D
v3d = [1, 2, 3]
 
# Vektor n-dimensi (fitur ML)
v_feature = [0.1, 0.5, -0.3, 0.8, 0.0]
 
print(f"Vektor 2D: {v2d}, dimensi: {len(v2d)}")
print(f"Vektor 3D: {v3d}, dimensi: {len(v3d)}")
print(f"Fitur: {v_feature}, dimensi: {len(v_feature)}")

Class Vec2

Mari kita bangun class Vec2 untuk operasi vektor 2D:

PythonVec2 class — operasi vektor 2D
import math
 
class Vec2:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
    def __add__(self, other):
        return Vec2(self.x + other.x, self.y + other.y)
 
    def __sub__(self, other):
        return Vec2(self.x - other.x, self.y - other.y)
 
    def __mul__(self, scalar):
        return Vec2(self.x * scalar, self.y * scalar)
 
    def magnitude(self):
        return math.sqrt(self.x**2 + self.y**2)
 
    def normalize(self):
        mag = self.magnitude()
        if mag == 0:
            return Vec2(0, 0)
        return Vec2(self.x / mag, self.y / mag)
 
    def dot(self, other):
        return self.x * other.x + self.y * other.y
 
    def distance_to(self, other):
        return (self - other).magnitude()
 
    def __repr__(self):
        return f"Vec2({self.x:.2f}, {self.y:.2f})"

Operasi Vektor

Penjumlahan dan Pengurangan

PythonPenjumlahan dan pengurangan vektor
a = Vec2(3, 4)
b = Vec2(1, 2)
 
print(f"a + b = {a + b}")    # Vec2(4.00, 6.00)
print(f"a - b = {a - b}")    # Vec2(2.00, 2.00)
print(f"a × 2 = {a * 2}")   # Vec2(6.00, 8.00)

Magnitude (Panjang Vektor)

PythonMagnitude dan distance
a = Vec2(3, 4)
print(f"Magnitude of {a}: {a.magnitude()}")  # 5.0 — Pythagoras!
 
origin = Vec2(0, 0)
point = Vec2(3, 4)
print(f"Jarak dari origin: {origin.distance_to(point)}")  # 5.0

Normalisasi

Normalisasi menghasilkan vektor dengan magnitude 1 (unit vector) — mempertahankan arah, menghapus panjang:

PythonNormalisasi vektor
direction = Vec2(3, 4)
unit = direction.normalize()
 
print(f"Original: {direction}, magnitude: {direction.magnitude():.2f}")
print(f"Normalized: {unit}, magnitude: {unit.magnitude():.2f}")

Dot Product

Dot product a · b = ax×bx + ay×by mengukur kemiripan arah:

PythonDot product — kemiripan arah
a = Vec2(1, 0)  # horizontal ke kanan
b = Vec2(0, 1)  # vertikal ke atas
c = Vec2(1, 1)  # diagonal
 
print(f"a · b = {a.dot(b)}")  # 0 — tegak lurus (90°)
print(f"a · c = {a.dot(c)}")  # 1 — 45°
print(f"a · a = {a.dot(a)}")  # 1 — sejajar sempurna
 
# cos(θ) = (a · b) / (|a| × |b|)
cos_angle = a.dot(b) / (a.magnitude() * b.magnitude())
angle_rad = math.acos(max(-1, min(1, cos_angle)))  # clamp untuk numerik
print(f"Sudut antara a dan b: {math.degrees(angle_rad):.1f}°")

Aplikasi dalam Game

Posisi dan Kecepatan

PythonGame physics sederhana — posisi dan kecepatan
class GameObject:
    def __init__(self, pos, vel):
        self.pos = pos    # Vec2 — posisi
        self.vel = vel    # Vec2 — kecepatan (unit/detik)
 
    def update(self, dt):
        """Update posisi: pos += vel × dt."""
        self.pos = self.pos + self.vel * dt
 
    def distance_to(self, other):
        return self.pos.distance_to(other.pos)
 
# Simulasi
player = GameObject(Vec2(0, 0), Vec2(5, 3))    # 5 unit/detik horizontal, 3 vertikal
enemy = GameObject(Vec2(20, 10), Vec2(-2, -1))  # mendekati player
 
print("Simulasi game:")
for t in range(5):
    player.update(1)
    enemy.update(1)
    dist = player.distance_to(enemy)
    print(f"  t={t+1}s: player={player.pos}, enemy={enemy.pos}, dist={dist:.2f}")

Pathfinding Direction

PythonArah ke target — normalisasi vektor
def direction_to_target(current, target):
    """Hitung arah normalisasi dari current ke target."""
    diff = target - current
    return diff.normalize()
 
player = Vec2(3, 4)
target = Vec2(10, 8)
 
dir = direction_to_target(player, target)
print(f"Arah ke target: {dir}")
print(f"Unit vector magnitude: {dir.magnitude():.2f}")
 
# Gerakkan player ke arah target
speed = 5  # unit/detik
new_pos = player + dir * speed
print(f"Setelah 1 detik: {new_pos}")

Aplikasi dalam ML

Feature Vektor

PythonFeature vector — representasi data sebagai vektor
# User features: [age, income, purchases, days_active]
user_a = Vec2(25, 50000, 10, 30)
user_b = Vec2(30, 75000, 25, 90)
 
# Similarity — cosine similarity via dot product
def cosine_similarity(a, b):
    return a.dot(b) / (a.magnitude() * b.magnitude())
 
# Note: Vec2 hanya punya 2 dimensi, gunakan list untuk lebih
def cosine_sim_list(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    mag_a = math.sqrt(sum(x**2 for x in a))
    mag_b = math.sqrt(sum(x**2 for x in b))
    return dot / (mag_a * mag_b) if mag_a and mag_b else 0
 
user_a_features = [25, 50, 10, 30]
user_b_features = [30, 75, 25, 90]
user_c_features = [22, 45, 8, 25]
 
print(f"Similarity A-B: {cosine_sim_list(user_a_features, user_b_features):.4f}")
print(f"Similarity A-C: {cosine_sim_list(user_a_features, user_c_features):.4f}")

Tip

Dot product adalah operasi paling fundamental dalam linear algebra untuk programming — ia muncul dalam cosine similarity (ML), shading (graphics), dan attention mechanism (transformers). Jika kalian menguasai dot product, kalian sudah memahami 50% dari linear algebra yang dibutuhkan.

Penutup

Inti yang harus dibawa pulang:

  • Vektor merepresentasikan arah dan magnitudo — array dalam program secara konseptual adalah vektor.
  • Penjumlahan vektor = komposisi perpindahan; skalar multiplication = rescaling.
  • Magnitude (|v|) = panjang vektor (Pythagoras); normalisasi = unit vector (magnitude 1).
  • Dot product mengukur kemiripan arah: 0 = tegak lurus, positif = searah, negatif = berlawanan.
  • Vektor muncul di game physics (posisi/kecepatan), ML (feature vectors, similarity), dan graphics (direction, normal).

Di episode 17 selanjutnya kita akan mempelajari matrix (matriks) — representasi 2D dari data, penjumlahan, perkalian skalar, dan perkalian matriks. Matriks adalah generalisasi vektor ke dimensi lebih tinggi dan fondasi dari image processing, transformasi geometri, dan data tables!

Belajar Math - Vectors (Vektor) | Belajar Math