OCaml mod函数与%相比返回不同的结果 [英] OCaml mod function returns different result compared with %
问题描述
与 python 中的模运算符相比, OCaml mod
中的模函数返回的结果有所不同.
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
为什么结果不同?.
在OCaml中是否有任何标准模块功能可以用作%
?
Is there any standard module function that operate as %
in OCaml?.
推荐答案
Python在%
运算符的用法上有点不同,该运算符实际上计算两个值的 modulo ,而其他运算符编程语言使用相同的运算符计算 remainder .例如,Scheme中的区别很明显:
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
在Python中:
-1 % 4 # modulo
=> 3
math.fmod(-1, 4) # remainder
=> -1
但是根据此文档:
-1 mod 4 (* remainder *)
=> -1
当然,您可以根据remainder
来实现自己的modulo
操作,如下所示:
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
这篇关于OCaml mod函数与%相比返回不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!