-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-normalize-a-direction.swift
More file actions
43 lines (34 loc) · 1.68 KB
/
Copy path02-normalize-a-direction.swift
File metadata and controls
43 lines (34 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import Playgrounds
import Quiver
// Normalize a Direction
// Normalization separates "how much" from "which way."
// A unit vector has length 1 and points in the same direction.
#Playground("Normalize a Direction") {
// A velocity vector: 3 units east, 4 units north
let velocity = [3.0, 4.0]
let speed = velocity.magnitude // 5.0 (the "how much")
print("Speed: \(speed)")
// Normalize: divide each component by the magnitude
// [3/5, 4/5] = [0.6, 0.8] — same direction, length = 1.0
let direction = velocity.normalized // [0.6, 0.8]
// Verify: the unit vector's magnitude is exactly 1.0
let check = direction.magnitude // 1.0
// Why this matters: now we can apply any speed we want.
// Scalar multiplication scales every component equally —
// the direction stays the same, only the magnitude changes
let newSpeed = 10.0
let newVelocity = newSpeed * direction // [6.0, 8.0]
// The new velocity has magnitude 10.0, same direction as original
let verifySpeed = newVelocity.magnitude // 10.0
// Decimals hide the math. 0.6 doesn't tell you much.
// asFractions() converts each element to its rational form,
// revealing that the unit vector is exactly [3/5, 4/5] —
// the Pythagorean triple divided by the hypotenuse.
// Useful for verification, teaching, and chart labels.
let fractions = direction.asFractions() // [3/5, 4/5]
print("Direction: \(direction)") // [0.6, 0.8]
print("Fractions: \(fractions)") // [3/5, 4/5]
print("Unit length: \(check)") // 1.0
print("At speed 10: \(newVelocity)") // [6.0, 8.0]
print("New speed: \(verifySpeed)") // 10.0
}