Mod: what changed
Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.
| Old | New | Line | |
|---|---|---|---|
| 1 | 1 | Back to [[Reserved words]]. | |
| 2 | 2 | ||
| 3 | 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 | 4 | ||
| 5 | 5 | From the [language reference](http://freepascal.org/docs-html/current/ref/refsu45.html#x148-17000012.8.1): | |
| 6 | 6 | ||
| 7 | 7 | ||
| 8 | 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 | 9 | ||
| 10 | - | ||
| 10 | + | ```text | |
| 11 | + | I mod J = I - (I div J) * J | |
| 12 | + | ``` | |
| 11 | 13 | ||
| 12 | 14 | For example "c:= -13 mod 4;" results in c = -1 and "c:= 10 mod -3;" results in c = 1. | |
| 13 | 15 | ||
| 14 | 16 | This is also what most other languages like C++ and Java do (see note) | |
| 15 | 17 | ||
| 16 | 18 | From version 3.1.1 FreePascal also supports the mod operator for floating point values when you include the math unit.\ | |
| 17 | 19 | 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 | 20 | ||
| 19 | 21 | The result is the same as the fmod function for the highest precision available for the platform. | |
| 20 | 22 | ||
| 21 | 23 | In older versions of FPC that support operator overloading you can add this feature yourself. Here's an example for double precision modulo. | |
| 22 | 24 | ||
| 23 | 25 | ``` pascal | |
| 24 | 26 | operator mod(const a, b: double) c: double; inline; | |
| 25 | 27 | begin | |
| 26 | 28 | c:= a - b * Int(a / b); | |
| 27 | 29 | end; | |
| 28 | 30 | ``` | |
| 29 | 31 | ||
| 30 | 32 | ## Note regarding Delphi compatibility | |
| 31 | 33 | ||
| 32 | 34 | Delphi conforms to ISO 7185 Pascal instead of the de facto standard. This ISO standard states: | |
| 33 | 35 | ||
| 34 | 36 | ||
| 35 | 37 | 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 | 38 | ||
| 37 | - | ||
| 39 | + | ```text | |
| 40 | + | 0 <= x mod y = x - k * y < y. | |
| 41 | + | ``` | |
| 38 | 42 | ||
| 39 | 43 | That means that in Delphi "c:= 10 mod -3;" results in an error and an exception will be thrown at run-time. | |
| 40 | 44 | ||
| 41 | 45 | --- | |
| 42 | 46 | *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).* |
