Mod: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Mod
| Old | New | Line | |
|---|---|---|---|
| 1 | + | Back to [[Reserved words]]. | |
| 2 | + | ||
| 3 | + | Mod (**mod**ulus) divides two numbers and returns only the remainder. For instance, the expression "a:= 13 mod 4;" would evaluate to 1 (a=1), while "b := 12 mod 4;" would evaluate to 0 (b=0). | |
| 4 | + | ||
| 5 | + | From the [language reference](http://freepascal.org/docs-html/current/ref/refsu45.html#x148-17000012.8.1): | |
| 6 | + | ||
| 7 | + | ||
| 8 | + | "The sign of the result of a Mod operator is the same as the sign of the left side operand of the Mod operator. In fact, the Mod operator is equivalent to the following operation :" | |
| 9 | + | ||
| 10 | + | ` I mod J = I - (I div J) * J` | |
| 11 | + | ||
| 12 | + | For example "c:= -13 mod 4;" results in c = -1 and "c:= 10 mod -3;" results in c = 1. | |
| 13 | + | ||
| 14 | + | This is also what most other languages like C++ and Java do (see note) | |
| 15 | + | ||
| 16 | + | From version 3.1.1 FreePascal also supports the mod operator for floating point values when you include the math unit.\ | |
| 17 | + | The precision used is the highest precision available for the platform. for instance, the expression "a:= 12.9 mod 2.2;" would evaluate to 1.9. This is equivalent to I mod J = I - int(I / J) * J. | |
| 18 | + | ||
| 19 | + | The result is the same as the fmod function for the highest precision available for the platform. | |
| 20 | + | ||
| 21 | + | In older versions of FPC that support operator overloading you can add this feature yourself. Here's an example for double precision modulo. | |
| 22 | + | ||
| 23 | + | ``` pascal | |
| 24 | + | operator mod(const a, b: double) c: double; inline; | |
| 25 | + | begin | |
| 26 | + | c:= a - b * Int(a / b); | |
| 27 | + | end; | |
| 28 | + | ``` | |
| 29 | + | ||
| 30 | + | ## Note regarding Delphi compatibility | |
| 31 | + | ||
| 32 | + | Delphi conforms to ISO 7185 Pascal instead of the de facto standard. This ISO standard states: | |
| 33 | + | ||
| 34 | + | ||
| 35 | + | Evaluation of a term of the form x mod y is an error if y is less than or equal to zero; otherwise there is an integer k such that x mod y satisfies the following relation: | |
| 36 | + | ||
| 37 | + | ` 0 <= x mod y = x - k * y < y.` | |
| 38 | + | ||
| 39 | + | That means that in Delphi "c:= 10 mod -3;" results in an error and an exception will be thrown at run-time. | |
| 40 | + | ||
| 41 | + | --- | |
| 42 | + | *From the Free Pascal wiki, page "Mod", as it stood on 2020-02-20 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
