-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.lisp
70 lines (59 loc) · 1.77 KB
/
vector.lisp
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
(in-package :math)
;;;; File containing vector operations
(defclass vec ()
((x :initarg :x
:initform 0d0
:reader x)
(y :initarg :y
:initform 0d0
:reader y)
(z :initarg :z
:initform 0d0
:reader z))
(:documentation "Three-dimensional vector"))
(defun vec (&optional &key (x 0d0) (y 0d0) (z 0d0))
"Create a new vector"
(make-instance 'vec
:x x
:y y
:z z))
(defun vec-p (instance)
"Check if something is a vector"
(typep instance 'vec))
(defun vec= (lhs rhs &optional &key (epsilon 1e-6))
"Compare two vectors with each other"
(and (float= (x lhs) (x rhs) :epsilon epsilon)
(float= (y lhs) (y rhs) :epsilon epsilon)
(float= (z lhs) (z rhs) :epsilon epsilon)))
(defmethod binary-add ((lhs vec) (rhs vec))
(vec :x (add (x lhs) (x rhs))
:y (add (y lhs) (y rhs))
:z (add (z lhs) (z rhs))))
(defmethod binary-diff ((lhs vec) (rhs vec))
(vec :x (diff (x lhs) (x rhs))
:y (diff (y lhs) (y rhs))
:z (diff (z lhs) (z rhs))))
(defmethod binary-mult ((lhs vec) rhs)
(vec :x (mult (x lhs) rhs)
:y (mult (y lhs) rhs)
:z (mult (z lhs) rhs)))
(defun vec-length (vector)
"Determine the length of a vector"
(sqrt (+ (expt (x vector) 2)
(expt (y vector) 2)
(expt (z vector) 2))))
(defun unit (vector)
"Convert a vector into a unit vector"
(let ((length (vec-length vector)))
(vec :x (/ (x vector) length)
:y (/ (y vector) length)
:z (/ (z vector) length))))
(defmethod print-object ((vector vec) stream)
"Print a vector"
(format stream
(if *print-readably*
"(vec :x ~a :y ~a :z ~a)"
"(~a; ~a; ~a)")
(x vector)
(y vector)
(z vector)))