From 10439934d496cae64f727b2cadf2580645e4d9a6 Mon Sep 17 00:00:00 2001 From: "alonso.torres" Date: Wed, 4 Jan 2023 16:18:12 +0100 Subject: [PATCH] :zap: Use the function `hypot` for distances --- common/src/app/common/geom/point.cljc | 6 ++---- common/src/app/common/geom/shapes/path.cljc | 2 +- common/src/app/common/math.cljc | 9 ++++++++- frontend/src/app/util/svg.cljs | 3 +-- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/common/src/app/common/geom/point.cljc b/common/src/app/common/geom/point.cljc index bfc55dc6d..5dd41501e 100644 --- a/common/src/app/common/geom/point.cljc +++ b/common/src/app/common/geom/point.cljc @@ -170,8 +170,7 @@ (dm/get-prop p2 :x)) dy (- (dm/get-prop p1 :y) (dm/get-prop p2 :y))] - (mth/sqrt (+ (mth/pow dx 2) - (mth/pow dy 2))))) + (mth/hypot dx dy))) (defn distance-vector "Calculate the distance, separated x and y." @@ -191,8 +190,7 @@ (assert (point? pt) "point instance expected") (let [x (dm/get-prop pt :x) y (dm/get-prop pt :y)] - (mth/sqrt (+ (mth/pow x 2) - (mth/pow y 2))))) + (mth/hypot x y))) (defn angle "Returns the smaller angle between two vectors. diff --git a/common/src/app/common/geom/shapes/path.cljc b/common/src/app/common/geom/shapes/path.cljc index 9178f2774..830e98e76 100644 --- a/common/src/app/common/geom/shapes/path.cljc +++ b/common/src/app/common/geom/shapes/path.cljc @@ -117,7 +117,7 @@ [x y] (->> coords (mapv solve-derivative)) ;; normalize value - d (mth/sqrt (+ (* x x) (* y y)))] + d (mth/hypot x y)] (if (mth/almost-zero? d) (gpt/point 0 0) diff --git a/common/src/app/common/math.cljc b/common/src/app/common/math.cljc index eee928bd9..03525d4d3 100644 --- a/common/src/app/common/math.cljc +++ b/common/src/app/common/math.cljc @@ -139,12 +139,18 @@ #?(:cljs (math/toDegrees radians) :clj (Math/toDegrees radians))) +(defn hypot + "Square root of the squares addition" + [a b] + #?(:cljs (js/Math.hypot a b) + :clj (Math/hypot a b))) + (defn distance "Calculate the distance between two points." [[x1 y1] [x2 y2]] (let [dx (- x1 x2) dy (- y1 y2)] - (-> (sqrt (+ (pow dx 2) (pow dy 2))) + (-> (hypot dx dy) (precision 2)))) (defn log10 @@ -182,3 +188,4 @@ "Get the sign (+1 / -1) for the number" [n] (if (neg? n) -1 1)) + diff --git a/frontend/src/app/util/svg.cljs b/frontend/src/app/util/svg.cljs index 8056ddd33..04b23ebf0 100644 --- a/frontend/src/app/util/svg.cljs +++ b/frontend/src/app/util/svg.cljs @@ -890,8 +890,7 @@ (defn calculate-ratio ;; sqrt((actual-width)**2 + (actual-height)**2)/sqrt(2). [width height] - (/ (mth/sqrt (+ (mth/pow width 2) - (mth/pow height 2))) + (/ (mth/hypot width height) (mth/sqrt 2))) (defn fix-percents