The calculation rule of the keyword “div” is 什么是关键字 “div” 的计算规则.

huangapple go评论68阅读模式
英文:

KDB:What is the calculation rule of the keyword div

问题

今天我发现了关于kdb中div的一个有趣现象

a:2 div 2.4
b:2.0 div 2.4

a和b的结果是不同的。
KDB官方解释div如下:“返回不超过x%y的最大整数。”
在上面的示例中,2%2.4=0.83333...小于1,但a的结果是1。
我知道我漏掉了一些知识,但我没有找到相关内容,请帮助我,感谢您的帮助。

英文:

Today I found an interesting phenomenon about div in kdb

a:2 div 2.4
b:2.0 div 2.4

The results of a and b are different.
KDB officially explains div in this way:"Returns the greatest whole number that does not exceed x%y."
In the above example, 2%2.4=0.83333... is less than 1, but the result of a is 1.
I know I missed some knowledge, but I didn't find the relevant content, please help me, thank you for the help.

答案1

得分: 4

我认为这里发生的是类型提升。在你的第一个例子中,看起来2.4被转换为一个长整型(左参数的类型)通过四舍五入到2。

你可以看到一些其他例子:

q)2 div 1.9 // 1.9四舍五入为2
1
q)2 div 1.5 // 1.5四舍五入为2
1
q)2 div 1.49 // 1.49四舍五入为1
2

所以你可以看到右参数似乎被四舍五入到最接近的长整型,然后用于除法运算。

对于你的另一个例子,似乎保持浮点值不变,因为这是左参数的类型。
这在这里有一些模糊的提及:https://code.kx.com/q/ref/div/
"除了char、byte、short和real之外,(div)会保留第一个参数的类型。"

英文:

I think what's happening here is type promotion. In your first example it looks like 2.4 is getting converted to an a long int (the type of the left argument) by getting rounded down to 2.
You can see this with some other examples:

q)2 div 1.9 // 1.9 gets rounded to 2
1
q)2 div 1.5 // 1.5 gets rounded to 2
1
q)2 div 1.49 // 1.49 gets rounded to 1
2

So you can see the right argument seems to be getting rounded to the nearest long int, then that is what's used for division.

For your other example it appears to be leaving the float value unchanged because that's the type of the left argument.
This is, somewhat vaguely, alluded to here: https://code.kx.com/q/ref/div/
"Except for char, byte, short, and real, (div) preserves the type of the first argument."

huangapple
  • 本文由 发表于 2023年5月17日 11:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定