[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Floating point inaccuracies
- From: Patrick Rapin <toupie300@...>
- Date: Wed, 1 Dec 2010 20:45:52 +0100
> So, please, let us stop this thread. Thanks,
As the initiator of the current flame, I apologize for my bad
proposition and also ask to stop that off-topic discussion.
However, in my last post of yesterday which seems to have passed
completely unnoticed, I proposed to add a function in math table.
This feature certainly is worth discussing a little more. The
operation performed could be expressed as :
function math.compare(value1, value2, delta, equalres)
value2 = value2 or 0
delta = delta or 0
if equalres == nil then equalres = 0 end
if math.abs(value1-value2) <= delta then return equalres end
if value1 < value2 then return -1 end
if value1 > value2 then return 1 end
return 0/0 -- returns NaN when value1 or value2 is NaN
end
Such a little function could serve several purposes, illustrated with
the following examples:
-- 1) have a quick way to make a three state comparison between two numbers
local cmp = { [-1] = 'is smaller than', [0] = 'is equal to', [1] = 'is
bigger than' }
for i=1,5 do
print(string.format("%d %s %d", i, cmp[math.compare(i, 3)], 3))
end
-- 2) an easy way to deal with floating point inaccuracies :-)
v=0; for i=1,10 do v=v+0.1 end
print(v == 1, math.compare(v, 1), math.compare(v, 1, 1e-15),
math.compare(v, 1, 1e-15, false))
if not math.compare(v, 1, 1e-15, false) then print("nearly equal") end
-- 3) emulate the "sign" function found in most programming languages
for v=-3,2 do
print(string.format("Sign of %d is %+d", v, math.compare(v)))
end
-- 4) simplify the sort of a array, over several numerical keys
tab = {} -- generate a 20x3 table
for i=1,20 do
local t = {}
for j=1,3 do t[j] = math.floor(math.random()*3) end
tab[i] = t
end
local function comp(t1, t2) -- note the single expression in the
sorting function!
return (math.compare(t1[1], t2[1], 0, false) or math.compare(t1[2],
t2[2], 0, false)
or math.compare(t1[3], t2[3])) < 0
end
table.sort(tab, comp)
for i=1,#tab do -- dump resulting table
local t = tab[i]
print(string.format("%2d: %d, %d, %d", i, t[1], t[2], t[3]))
end