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

牧云@^-^@ 提交于 2019-12-07 20:05:24

问题


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:


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.



来源:https://stackoverflow.com/questions/30733829/mysql-mod-is-broken-is-this-the-best-alternative

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!