Skip to content

Commit d36dca3

Browse files
authored
Optimize vector length calculations (#11549)
1 parent a7188bd commit d36dca3

File tree

2 files changed

+3
-10
lines changed

2 files changed

+3
-10
lines changed

builtin/common/misc_helpers.lua

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -209,14 +209,7 @@ end
209209

210210
--------------------------------------------------------------------------------
211211
function math.hypot(x, y)
212-
local t
213-
x = math.abs(x)
214-
y = math.abs(y)
215-
t = math.min(x, y)
216-
x = math.max(x, y)
217-
if x == 0 then return 0 end
218-
t = t / x
219-
return x * math.sqrt(1 + t * t)
212+
return math.sqrt(x * x + y * y)
220213
end
221214

222215
--------------------------------------------------------------------------------

builtin/common/vector.lua

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ metatable.__eq = vector.equals
6767
-- unary operations
6868

6969
function vector.length(v)
70-
return math.hypot(v.x, math.hypot(v.y, v.z))
70+
return math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z)
7171
end
7272
-- Note: we can not use __len because it is already used for primitive table length
7373

@@ -104,7 +104,7 @@ function vector.distance(a, b)
104104
local x = a.x - b.x
105105
local y = a.y - b.y
106106
local z = a.z - b.z
107-
return math.hypot(x, math.hypot(y, z))
107+
return math.sqrt(x * x + y * y + z * z)
108108
end
109109

110110
function vector.direction(pos1, pos2)

0 commit comments

Comments
 (0)