double d = 0; // random decimal value with it's integral part within the range of Int32 and always positive.
int floored = (int) Math.Floor(d); // Less than or equal to.
int ceiled = (int) Math.Ceiling(d); // Greater than or equal to.
int lessThan = ? // Less than.
int moreThan = ? // Greater than.
地板和天花板函数包括分别小于/大于或等于 d
的最大/最小整数。我想找出分别小于/大于但不等于 d
的最大/最小整数。
当然,这可以通过一些if's and but's
方法来实现,但我正在寻找一种不包括分支或至少非常快的方法,因为此操作将在算法中执行数十亿次。
二进制操作可能吗?如果没有,最好的选择是什么?
显而易见的解决方案是:
int lessThan = (d - floored) > double.Epsilon ? floored : (floored-1);
int moreThan = (ceiled - d) > double.Epsilon ? ceiled : (ceiled+1);
注意:目的是找出是否d
更接近lessThan
或moreThan
。