The underlying repository does use Python but this math can be definitely implemented with other languages. I hope you might find it usefull. It's to say - when reading correctly - that you need a quite up-to-date jupyter
version to work with this document. Let's start with 2d vector.
Please check the repository for concept/math/vector.py
containing the Python class wrapping the math logic and simplifying the usage.
A vector basically provides two information:
The vector looks like $\vec{v} = \begin{pmatrix}v_x\\v_y \end{pmatrix}$ and the length of the vector is calculated by $|\vec{v}| = \sqrt{v_x \cdot v_x + v_y \cdot v_y}$
In [5]:
import math
len_vector = lambda vector: math.sqrt(vector[0]**2 + vector[1]**2)
vector = [3, 4]
print("vector is %s" % vector)
print("vector length is %g" % len_vector(vector))
In [5]:
sum_vector = lambda a, b: [a[0]+b[0], a[1]+b[1]]
diff_vector = lambda a, b: [a[0]-b[0], a[1]-b[1]]
vector_a = [1, 2]
vector_b = [3, 4]
print("%s + %s = %s" % (vector_a, vector_b, sum_vector(vector_a, vector_b)))
print("%s - %s = %s" % (vector_a, vector_b, diff_vector(vector_a, vector_b)))
There are different kind of products:
In [10]:
scale_vector = lambda f, v: [f * v[0], f * v[1]]
scalar_product = lambda a, b: a[0]*b[0] + a[1]*b[1]
cross_product = lambda a, b: a[0]*b[1] - a[1]*b[0]
print("%g * %s = %s" % (3, vector_a, scale_vector(3, vector_a)))
print("%s * %s = %s (scalar product)" % (vector_a, vector_b, scalar_product(vector_a, vector_b)))
print("%s x %s = %s (cross product)" % (vector_a, vector_b, cross_product(vector_a, vector_b)))
In [2]:
turned_Left = lambda v: [-v[1], v[0]]
turned_right = lambda v: [v[1], -v[0]]
vector = [0, 1]
print("%s rotated 90 degree counter clockwise: %s" % (vector, turned_Left(vector)))
print("%s rotated 90 degree clockwise: %s" % (vector, turned_right(vector)))
In [6]:
vector_angle = lambda u, v: math.atan2(u[1], u[0]) - math.atan2(v[1], v[0])
vector_a = [0, 1]
vector_b = [1, 0]
print("Angle between %s and %s is %g degree" \
% (vector_a, vector_b, vector_angle(vector_a, vector_b) * 180.0/math.pi))
In [11]:
vector_rotated = lambda v, a: [round(v[0] * math.cos(a) - v[1] * math.sin(a), 5),\
round(v[0] * math.sin(a) + v[1] * math.cos(a), 5)]
vector = [1, 0]
print("Angle %s rotated 90 degree to the left is %s" \
%(vector, vector_rotated(vector, 90 * math.pi / 180.0)))
print("Angle %s rotated 90 degree to the right is %s" \
%(vector, vector_rotated(vector, -90 * math.pi / 180.0)))
In [ ]: