MySQL MOD() is broken: Is this the best alternative?

943 views Asked by At

At least in MySQL v5.1.73 (CentOS 6.6), MOD() function returns a bogus result... unless someone can explain how this is actually correct.

mysql> select MOD(-385.4784399 ,1440);
+-------------------------+
| MOD(-385.4784399 ,1440) |
+-------------------------+
|            -385.4784399 |
+-------------------------+
1 row in set (0.01 sec)

Is this the best alternative?

mysql> select -385.478439885319 - 1440 * FLOOR(-385.478439885319/1440);
+----------------------------------------------------------+
| -385.478439885319 - 1440 * FLOOR(-385.478439885319/1440) |
+----------------------------------------------------------+
|                                        1054.521560114681 |
+----------------------------------------------------------+
1 row in set (0.00 sec)

I think this will work as well, but it's all going the long way around to do something simple.

mysql> select MOD((MOD(-385.478439885319, 1440) + 1440), 1440);
+--------------------------------------------------+
| MOD((MOD(-385.478439885319, 1440) + 1440), 1440) |
+--------------------------------------------------+
|                                1054.521560114681 |
+--------------------------------------------------+
1 row in set (0.00 sec)
1

There are 1 answers

1
mclark1129 On BEST ANSWER

MySQL isn't giving you a bogus result, it's simply using a different implementation of modulus than you are expecting. Unfortunately the term modulus seems to have been defined somewhat ambiguously, and it's implementation varies from language to language. From what I can tell in the Wikipedia on Modulo, MySQL's implementation is using truncated division:

r = a - n * trunc(a / n)

Where you are expecting the implementation to use floored division:

r = a - n * floor(a / n)

Since this how you implemented your first workaround, I'd say it's probably the best alternative to the Mod operator.

From what I've seen (and this is a very quick unscientific analysis!), it seems like more imperative programming languages implement truncated division and more functional mathematical languages seem to use floored division.