Theiling Online    Sitemap    Conlang Mailing List HQ   

Re: Programming a calendar system

From:Mark J. Reed <markjreed@...>
Date:Wednesday, April 28, 2004, 14:28
On Wed, Apr 28, 2004 at 02:06:51PM +0200, Carsten Becker wrote:
> What are the normal division and the modulo division good for? And what > would I have to write when 72 seconds ($asec) are 1 minute ($amin)?
Modulo gives you the remainder after the division, which is therefore the number of the next unit down. For instance, if I told you that 3,296 seconds had passed and asked you what that was in minutes and seconds, then you would divide by 60; the quotient is the number of minutes and the remainder is the number of seconds into the next minute. 3296 / 60 = 54 3296 % 60 = 56 so 3,296 seconds is 54 minutes and 56 seconds, or 4 seconds shy of 55 minutes. Exactly how you compute this depends on the language. In many C-like languages the type of the result of the '/' operator depends on the type of its operands, so 3296 / 60 = 54, but 3296.0 / 60.0 = 56.933333333 etc. In others the result of / is a float whenever the quotient is not exact, and you have to explicitly apply a function (usually "floor") to get integer form. Some languages have a function that returns both the quotient and the remainder in one go, which avoids having to do the division operation twice. Finally, care is required when dealing with negative numbers, and how you treat them depends on what you're looking for. For example, say that "time zero" is now, which means that something that happend 3,296 seconds ago is time -3296. When you do the division above, you wind up with -3296 / 60 and -3296 % 60. Now, what are the integer quotient and remainder of -3296 / 60? A plain "typecast" to an integer type will probably do truncation, also known as "round toward zero mode", and leave you with -54 and -56. But often what you want is "round down", which gives you -55 and +4. If, for instance, time zero is midnight and you want to know what time of day it was at -3,296 seconds, the correct answer is 23:05:04, which is easy to get from the second pair of results but less easy to achieve from the first. So it's often a good idea to ignore the modulus operator provided by the language and define your own such that mod(x, y) = x - y * floor(x/y). which has the additional advantage of working on non-integers. -Mark

Reply

Joe <joe@...>