R 理解模运算符的结果:%%

R 理解模运算符的结果:%%,r,operators,R,Operators,我正在寻找在R语言中应用于%%运算符的方法 10 %% 10 # 0 20 %% 10 # 0 对这两个结果表示怀疑: 10 %% 20 # 10 2 %% 8 # 2 你能帮我更好地理解最后两个结果吗?我有点困惑 没什么错: 10 = 1 * 10 + 0 20 = 2 * 10 + 0 10 = 0 * 20 + 10 2 = 0 * 8 + 2 模是+后面的数字 通常,对于两个编号a和b,有 a = floor(a / b) * b + (a %% b) 让我们编写

我正在寻找在R语言中应用于%%运算符的方法

10 %% 10  # 0
20 %% 10  # 0
对这两个结果表示怀疑:

10 %% 20  # 10
2 %% 8  # 2
你能帮我更好地理解最后两个结果吗?我有点困惑

没什么错:

10 = 1 * 10 + 0
20 = 2 * 10 + 0
10 = 0 * 20 + 10
2  = 0 * 8  + 2 
模是
+
后面的数字


通常,对于两个编号
a
b
,有

a = floor(a / b) * b + (a %% b)
让我们编写一个玩具函数:

foo <- function(a,b) c(quotient = floor(a / b), modulo = a %% b)

foo(10, 10)
#quotient   modulo 
#   1        0 

foo(20, 10)
#quotient   modulo 
#   2        0 

foo(10, 20)
#quotient   modulo 
#   0       10 

foo(2, 8)
#quotient   modulo 
#   0        2 

foo试图理解模为x的R中的一些结果,我找到了这一页。然后试图向自己解释一些“querky”结果,我在下面写了这个R脚本。我曾读到模运算符的余数或结果应该总是正的,但在R中不是这样,这里提供的定义和示例解释了似乎使用的逻辑。定义“x mod y=x-(| x/y |*y)”其中| x/y |=floor(x/y)在R中似乎总是正确的,或者以更标准的方式,操作q=x/y的余数“R”的定义是x=kq+R,其中k和R都是整数。
我的剧本评论是用法语写的,结果很糟糕,所以我把它们删掉了,但这不是理解的必要条件。。。
基本上在R中,x=2,y=-5,x模y=-3;或者使用定义x=kq+r,我们得到r=x-kq=-3。
然而,这在数学意义上是一种质疑,因为“整数部分积”(kq)实际上超过了被除数(x),因此将余数(r)定义为负整数

x语法
我也很困惑,但如果您知道%%运算符的结果是除法的余数,那就很容易了

例如,75%%4=3

我注意到如果除数小于除数,那么R返回相同的除数值

例4%%75=4

10%%20=10 2%%8=2

干杯


虽然李振远给出了一个很好的答案,但我认为你所做的只是混淆了论点的顺序。如果您希望
10%%20
返回0,那么您可能实际上想要执行
20%%10
remainder <- dividend %% divisor
12 %% 11
# quotient is 1.090909
# remainder is 1

12 %% 10
# quotient is 1.2
# remainder is 2

12 %% 9
# quotient is 1.333333
# remainder is 3

12 %% 8
# quotient is 1.5
# remainder is 4

12 %% 7
# quotient is 1.714286
# remainder is 5

12 %% 6
# quotient is 2
# remainder is 0
# 12 is divisible by 6

12 %% 5
# quotient is 2.4
# remainder is 2

12 %% 4
# quotient is 3
# remainder is 0
# 12 is divisible by 4

12 %% 3
# quotient is 4
# remainder is 0
# 12 is divisible by 3

12 %% 2
# quotient is 6
# remainder is 0
# 12 is divisible by 2

12 %% 1
# quotient is 12
# remainder is 0
# any whole number is divisible by 1