Advertisement
Guest User

Vector stuff

a guest
Apr 22nd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns collijion.planet
  2.   (:import [clojure.lang PersistentVector]))
  3.  
  4. #_(def G 6.674E-11)
  5. (def G 7E-5)
  6.  
  7. (defrecord Planet [m r x y ^PersistentVector v])
  8.  
  9. (defn add
  10.   "Adds together an arbitrary amount of vectors"
  11.   [& colls]
  12.   (reduce (partial mapv +) colls))
  13.  
  14. (defn sub
  15.   "Subtracts an arbitrary amount of vectors"
  16.   [& colls]
  17.   (reduce (partial mapv -) colls))
  18.  
  19. (defn mult
  20.   "Multiplies a vector by a number"
  21.   [v n]
  22.   (mapv #(* % n) v))
  23.  
  24. (defn div
  25.   "Divides a vector by a number"
  26.   [v n]
  27.   (when-not (= n 0)
  28.    (mapv #(/ % n) v)))
  29.  
  30. (defn distance
  31.   "Calculates the Euclidean distance between
  32.  two points"
  33.   [p1 p2]
  34.   (Math/sqrt
  35.    (+ (Math/pow (- (:x p1) (:x p2)) 2)
  36.       (Math/pow (- (:y p1) (:y p2)) 2))))
  37.  
  38. (defn magnitude
  39.   "Calculates the magnitude of a vector"
  40.   [[x y]]
  41.   (Math/sqrt (+ (Math/pow x 2) (Math/pow y 2))))
  42.  
  43. (defn unit
  44.   "Calculates the unit vector of a vector"
  45.   [v]
  46.   (let [m (magnitude v)]
  47.     (if (= m 0)
  48.       [0 0]
  49.       (div v m))))
  50.  
  51. (defn grav-vec
  52.   "Calculates the attraction force between two
  53.  bodies using Newton's law of universal gravitation.
  54.  Force applied on object 2 exerted by object 1."
  55.   [p1 p2]
  56.   (let [dist (distance p1 p2)]
  57.     (mult
  58.      (div (sub (:v p1) (:v p2)) dist)
  59.      (* (- G)
  60.        (/ (* (:m p1) (:m p2))
  61.           (Math/pow dist 2))))))
  62.  
  63. (defn gen-f-vec
  64.   "Calculate all force vectors for all objects in
  65.  a vector"
  66.   [planets]
  67.   (partition (dec (count planets))
  68.    (for [p1 planets p2 planets
  69.          :when (not= p1 p2)]
  70.      (grav-vec p1 p2)))) ;check this application
  71.  
  72. (defn apply-forces
  73.   "Apply all the force vectors to the planets"
  74.   [planets forces]
  75.   (let [sum-forces (fn [old fl] (reduce add old fl))
  76.         zip (fn [planet force-list]
  77.               (update planet :v sum-forces force-list))]
  78.    (map zip planets forces)))
  79.  
  80. (defn apply-speed
  81.   "Applies the new velocity to the planets"
  82.   [planets]
  83.   (let [move (fn [{[vx vy] :v :as p}]
  84.                (-> p
  85.                 (update :x #(+ % vx))
  86.                 (update :y #(+ % vy))))]
  87.     (map move planets)))
  88.  
  89. (defn update-planets
  90.   "Update all planets velocity vectors
  91.  and coordinates"
  92.   [planets]
  93.   (apply-speed (apply-forces planets (gen-f-vec planets))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement