JavaME 函数帮助
谁能向我解释一下这个 MIDP Java 函数是如何工作的?我对所使用的运算符特别好奇。
public static final int smoothDivide(int numerator, int denominator) {
return (int) ((numerator << 16) / denominator + 32768L) >> 16;
}
多谢
Could anyone explain to me how this MIDP Java function works? I'm particularly curious about the operators being used.
public static final int smoothDivide(int numerator, int denominator) {
return (int) ((numerator << 16) / denominator + 32768L) >> 16;
}
Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一种四舍五入到最接近整数的除法算法。它相当于
一个大范围的整数,但巧妙地实现了没有浮点运算。
运算符
<<
和>>
为 按位左移和右移运算符。这是其工作原理的直觉
首先请注意
<< 16
和>> 16
分别相当于* 65536
和/65536
。因此,该算法的计算如下:也就是说,它按比例放大分子,除以分子,加上一半的比例,然后再次按比例缩小。
它类似于表达式
(int) ((numerator + 0.5) / denominator)
,这是进行“四舍五入”除法的更常见方法(但它依赖于浮点运算)。This is a division algorithm that rounds to the closest integer. It is equivalent to
for a large range of the integers, but cleaverly implemented without floating point operations.
The operators
<<
and>>
are bitwise shift left and shift right operators.Here is the intuition for how it works
First note that
<< 16
and>> 16
are equivalent to* 65536
and/ 65536
respectively. So what the algorithm computes is the folowing:That is, it scales up the numerator, divides it, adds half of the scale, and then scales it down again.
It is similar to the expression
(int) ((numerator + 0.5) / denominator)
which is a more common way to do "rounded" division (but it relies on floating point arithmetic).