lua-users home
lua-l archive

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


Paul Smith <paullocal@pscs.co.uk> writes:

> Bogdan Marinescu wrote:
>> Of course. But then again, Lua does provide a math library. So a
>> round' function would fit quite nicely in there :)
> Lua DOES have a 'round' function - 2 in fact .... math.floor() rounds
> down for you, and math.ceil() rounds up for you. :)
>
> If that's not what you want, you can write one to do what you want in
> a few seconds. Making a 'math.round' which rounds to the nearest
> integer is a couple of lines of code.

There is no nearest single integer for 1.5.  That's what rounding rules
are all about.  The closest for round-to-even would likely be something
like

function round(x)
  if x%2 ~= 0.5
    return math.floor(x+0.5)
  end
  return x-0.5
end

The problem with that is that it is likely to be vastly less efficient
than what a builtin rounding operation would usually look like.

> Lua is minimalist. math.round() can trivially be added to do what you
> want using the existing functions. The maths library is generally just
> stuff which is harder to do - eg making a math.floor() would actually
> be quite hard, as would math.cos, math.log etc.

When we are talking about being minimalist, math.floor(x) is just
-math.ceil(-x), so that's more expendable than math.round, really.

-- 
David Kastrup