lua-users home
lua-l archive

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

> function round(x)
>    local y = math.ceil(x - 0.5)
>    return x - y + y/2%1 < 1 and y or math.ceil(x)
> end

I'll take your word that it works, since you have a good
reputation for meticulous coding.

IMO, it is a bad habit to rely on people's reputation.
At least, on my reputation :-)
My function gives wrong result for round((1<<54)+3) and I didn't know that yesterday.

>> function round(x)
>>   local ans = math.floor(x)
>>   local err = x-ans
>>   if err<0.5 then return ans
>>   elseif err>0.5 then return ans+1
>>   elseif ans%2==0 then return ans
>>   else return ans+1
>>   end
>> end
> Yes, that's correct (but cumbersome).

At least one person besides the author could see at a glance
that the code is correct. I'll take 'cumbersome' any day if it can
give me that.

Relying on cumbersomeness is not a good idea also :-)
Your function will return wrong result for round(math.maxinteger + 0.75) on Lua built with 32-bit integer as LUA_INTEGER and double as LUA_NUMBER.
Can you fix your function so it would give correct result for any combination of LUA_INTEGER and LUA_NUMBER?