-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector_operations.pyx
90 lines (63 loc) · 2.62 KB
/
vector_operations.pyx
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# vector_operations.pyx
import cython
import numpy as np
cimport numpy as np
# Vector addition
cpdef np.ndarray[np.float64_t, ndim=1] vector_addition(np.ndarray[np.float64_t, ndim=1] a, np.ndarray[np.float64_t, ndim=1] b):
cdef int n = len(a)
cdef np.ndarray[np.float64_t, ndim=1] result = np.zeros(n, dtype=np.float64)
cdef int i
for i in range(n):
result[i] = a[i] + b[i]
return result
# Scalar multiplication
cpdef np.ndarray[np.float64_t, ndim=1] scalar_multiplication(np.ndarray[np.float64_t, ndim=1] a, float scalar):
cdef int n = len(a)
cdef np.ndarray[np.float64_t, ndim=1] result = np.zeros(n, dtype=np.float64)
cdef int i
for i in range(n):
result[i] = a[i] * scalar
return result
# Vector multiplication (element-wise)
cpdef np.ndarray[np.float64_t, ndim=1] vector_multiplication(np.ndarray[np.float64_t, ndim=1] a, np.ndarray[np.float64_t, ndim=1] b):
cdef int n = len(a)
cdef np.ndarray[np.float64_t, ndim=1] result = np.zeros(n, dtype=np.float64)
cdef int i
for i in range(n):
result[i] = a[i] * b[i]
return result
# Dot product
cpdef float dot_product(np.ndarray[np.float64_t, ndim=1] a, np.ndarray[np.float64_t, ndim=1] b):
cdef int n = len(a)
cdef float result = 0.0
cdef int i
for i in range(n):
result += a[i] * b[i]
return result
# Vector subtraction
cpdef np.ndarray[np.float64_t, ndim=1] vector_subtraction(np.ndarray[np.float64_t, ndim=1] a, np.ndarray[np.float64_t, ndim=1] b):
cdef int n = len(a)
cdef np.ndarray[np.float64_t, ndim=1] result = np.zeros(n, dtype=np.float64)
cdef int i
for i in range(n):
result[i] = a[i] - b[i]
return result
# Vector division (element-wise)
cpdef np.ndarray[np.float64_t, ndim=1] vector_division(np.ndarray[np.float64_t, ndim=1] a, np.ndarray[np.float64_t, ndim=1] b):
cdef int n = len(a)
cdef np.ndarray[np.float64_t, ndim=1] result = np.zeros(n, dtype=np.float64)
cdef int i
for i in range(n):
result[i] = a[i] / b[i]
return result
# Scalar component
cpdef np.ndarray[np.float64_t, ndim=1] scalar_component(np.ndarray[np.float64_t, ndim=1] a, np.ndarray[np.float64_t, ndim=1] b):
cdef float scalar = dot_product(a, b) / dot_product(b, b)
return scalar * b
# Cross product
cpdef np.ndarray[np.float64_t, ndim=1] cross_product(np.ndarray[np.float64_t, ndim=1] a, np.ndarray[np.float64_t, ndim=1] b):
cdef np.ndarray[np.float64_t, ndim=1] result = np.zeros(3, dtype=np.float64)
result[0] = a[1] * b[2] - a[2] * b[1]
result[1] = a[2] * b[0] - a[0] * b[2]
result[2] = a[0] * b[1] - a[1] * b[0]
return result