[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Integers, Modulus
- From: "Peter Hill" <corwin@...>
- Date: Thu, 20 Dec 2001 13:59:16 +0800
chbarr said:
> First, I wanted to get a modulus (remainder) of two numbers. I looked
> in the Lua Reference manual and Programming Lua, and no luck.
>
> So, I thought that, with some effort, I could work around that.
> However, I could not find how to take just the integer part of a
> floating number (i.e. the part to the left of the decimal point).
John Mckenna replied:
> You have floor() and ceil(). They can be used to do any integerising you
> need.
>
> I can never remember how mod is supposed to work when negative numbers are
> involved, so this might only work for positive numbers (that's all I ever
> use mod for anyway):
>
> result = a - b*floor(a/b)
Scott Morgan added:
> http://www.lua.org/manual/manual.html#6.3
> The 'mod' function is there, and appears in Plua.
You can get the "remainder" using EITHER "a-b*floor(a/b)" or "mod(a,b)"
however there IS a difference.
(a) "function rem(a,b) return a-b*floor(a/b) end" will always handle
negative numbers in a well defined and (generally) more useful fashion.
Specifically, the result always falls in the range [0,b).
(b) "mod" is, AFAIK, machine dependent (based on the hardware operations?)
and under PLua implements a common (but generally less useful) definiton. In
essence it depends on how you wish to round your integer division. Ie,
2/5 = 0.4, which is universally considered to be "0 remainder 2".
but
-2/5 = -0.4 which can be considered to be (a) "0 remainder -2" (since -2
= -1x5 + 3) or (b) "-1 remainder 3" (since -2 = 1x5 + -2).
Thus (under PLua):
rem(-2,5) = 3 [using "rem" defined above]
versus
mod(-2,5) = -2 [using the machine-dependent version]
Which you use depends on why you want the remainder.
For example, if I wanted to create a hash table in C mapping an arbitrary
integer "x" onto a C array "type hash_table[47];" then I would use
"rem(x,47)" to get the index as it produces a result 0..46 for all values of
"x" including negative ones.
*cheers*
Peter Hill.