lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>     norm = function (V) return math.sqrt(V[1]^2 + V[2]^2) end,
> 
> 
> Off topic: I though this was just an email typo yet the same is present in the
> link you provide. I am confused why a mathematician would use such a name for
> calculating the magnitude of a vector.

Since we're off-topic, I'd be more surprised to *not* use something like

local abs, sqrt = math.abs, math.sqrt
norm2 = function (V)
  local v1, v2 = abs(V[1]), abs(V[2])
  if v1 < v2 then v1, v2 = v2, v1 end -- v1 is max(V)
  local r = v2 / v1
  return v1 * sqrt(1 + r * r)
end

to avoid under/overflows:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> x = {1e100, 1e100}; print(norm(x), norm2(x))
1.4142135623731e+100  1.4142135623731e+100
> x = {1e200, 1e200}; print(norm(x), norm2(x))
inf 1.4142135623731e+200
> x = {1e-200, 1e-200}; print(norm(x), norm2(x))
0 1.4142135623731e-200

Cheers,
Luis

-- 
Computers are useless. They can only give you answers.
                -- Pablo Picasso

-- 
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'