正 System.Double 值的快速地板和天花板替代方案

Rah*_*han 5 .net c# double floor ceil

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.
Run Code Online (Sandbox Code Playgroud)

地板和天花板函数包括分别小于/大于或等于 的最大/最小整数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);
Run Code Online (Sandbox Code Playgroud)

注意:目的是找出是否d更接近lessThanmoreThan

har*_*old 3

由于d总是正数,因此您可以使用该转换为整数截断(即,它是正输入的下限和负输入的上限)。

floor(d + 1)与 相同ceil(d) + 1 if integer, ceil(d) otherwiseceil(d - 1)相同floor(d) - 1 if integer, floor(d) otherwise

int moreThan = (int)(d + 1); // floor(d + 1)
int lessThan = int.MaxValue + (int)((d - int.MaxValue) - 1) // ceil(d - 1)
Run Code Online (Sandbox Code Playgroud)

lessThan有点令人费解,如果其他人有更好的想法,我不会感到惊讶。

但既然你想要这个:

目标是找出 d 是否更接近 lessThan 或 moreThan

应该更简单:

double x = d % 1;
if (x == 0 || x == 0.5)
    // d is equally far from either one, either by a difference of 1 or of 0.5
else if (x < 0.5)
    // d is closer to lessThan
else
    // d is closer to moreThan
Run Code Online (Sandbox Code Playgroud)