OCaml mod function returns different result compared with %

*爱你&永不变心* 提交于 2019-12-23 10:15:30

问题


The modulo function in OCaml mod return results different when compared with the modulo operator in python.

OCaml:

# -1 mod 4
- : int = -1

Python:

>>> -1 % 4
3

Why are the result different?.

Is there any standard module function that operate as % in OCaml?.


回答1:


Python is a bit different in its usage of the % operator, which really computes the modulo of two values, whereas other programming languages compute the remainder with the same operator. For example, the distinction is clear in Scheme:

(modulo -1 4)    ; modulo
=> 3
(remainder -1 4) ; remainder
=> -1

In Python:

-1 % 4           # modulo
=> 3
math.fmod(-1, 4) # remainder
=> -1

But in OCaml, there's only mod (which computes the integer remainder), according to this table and as stated in the documentation:

-1 mod 4 (* remainder *)
=> -1

Of course, you can implement your own modulo operation in terms of remainder, like this:

let modulo x y =
  let result = x mod y in
  if result >= 0 then result
  else result + y



回答2:


The semantics of modulo are linked with the semantics of integer division (generally, if Q is the result of integer division a / b, and R is the result of a mod b, then a = Q * b + R must always be true), so different methods of rounding the result of integer division to an integer will produce different results for modulo.

The Wikipedia article Modulo operation has a very extensive table about how different languages handle modulo. There are a few common ways:

  • In languages like C, Java, OCaml, and many others, integer division rounds towards 0, which causes the result of modulo to always have the same sign as the dividend. In this case, the dividend (-1) is negative, so the modulo is also negative (-1).

  • In languages like Python, Ruby, and many others, integer division always rounds down (towards negative infinity), which causes the result of modulo to always have the same sign as the divisor. In this case, the divisor (4) is positive, so the modulo is also positive (3).



来源:https://stackoverflow.com/questions/46758683/ocaml-mod-function-returns-different-result-compared-with

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