gpt4 book ai didi

c# - 正 System.Double 值的快速下限和上限替代方案

转载 作者:行者123 更新时间:2023-11-30 12:13:17 26 4
gpt4 key购买 nike

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.

Floor 和 ceiling 函数包括分别小于/大于或等于 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是否更接近lessThanmoreThan

最佳答案

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

floor(d + 1)ceil(d) + 1 如果是整数,ceil(d) 否则相同ceil(d - 1 )floor(d) 相同 - 如果是整数则为 1,否则为 floor(d)

int moreThan = (int)(d + 1); // floor(d + 1)
int lessThan = int.MaxValue + (int)((d - int.MaxValue) - 1) // ceil(d - 1)

lessThan 有点复杂,如果有人有更好的主意,我不会感到惊讶。

但是既然你想要这个:

The objective is to find out whether d is closer to lessThan or 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

关于c# - 正 System.Double 值的快速下限和上限替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11923135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com