9

假设我有一个浮点数 X。我想找到小于 X 并且可以无损存储在浮点数中的最大数。

IIRC IEEE 标准说,您可以通过将浮点数的位转换为 int 表示、减一并转换回浮点数来实现这一点。

编辑:这对于非 NaN 或 inf 的正数是正确的。对于负数,您必须添加。有关更多信息,请参阅Rawling 的答案。)

要在表示之间进行更改,我只知道 C# 的 (cast) 运算符,它会截断。那不是我想要的。

有没有办法在 C# 中做到这一点?

4

2 回答 2

9

以下是您如何简单地将 afloat变成 a int,对其进行更改,然后将其重新变成 a 的方法float

float myFloat = 10.3f;
// Get the bytes making up the float
byte[] bytes = BitConverter.GetBytes(myFloat);
// Make an int out of them
int myInt = BitConverter.ToInt32(bytes, 0);
// Change it
myInt--;
// Get the bytes making up the int
bytes = BitConverter.GetBytes(myInt);
// Make a float out of them
myFloat = BitConverter.ToSingle(bytes, 0);
// gives 10.2999992 or so

BitConverter甚至为 64 位等价物内置了这个:

double myDouble = 10.3;
long myLong = BitConverter.DoubleToInt64Bits(myDouble);
myLong--;
myDouble = BitConverter.Int64BitsToDouble(myLong); // gives 10.2999999...

然而,正如Peter Ruderman指出的那样,简单的底层证券递减int并不能可靠地为您提供下一个最小的float.

特别是,对于负数,您需要增加整数以使浮点数更负。对于float零,下一个最小值int实际上对应于NaN,因此您需要一个特殊情况。

以下是我拼凑起来的几个函数,它们通常可以应对这些情况;它看起来也很明智地在大数和正/负无穷大之间移动!我使用了不安全的转换来减少代码长度,但如果你愿意,你可以坚持上面的字节转换:

static unsafe float Increment(float f)
{
    int val = *(int*)&f;
    if (f > 0)
        val++;
    else if (f < 0)
        val--;
    else if (f == 0)
        return float.Epsilon;
    return *(float*)&val;
}
static unsafe float Decrement(float f)
{
    int val = *(int*)&f;
    if (f > 0)
        val--;
    else if (f < 0)
        val++;
    else if (f == 0)
        return -float.Epsilon; // thanks to Sebastian Negraszus
    return *(float*)&val;
}

正如Jeppe指出的那样,您可能还想

  • 以 开始每个函数if (float.IsNaN(f)) return f;,这样您就不会意外地递增或递减 aNaN并给出一个数字。
  • 还要考虑对照float.PositiveInfinityor检查输入.NegativeInfinity,因为从数学上讲,这些应该在递增/递减下保持不变。
于 2013-01-11T12:36:53.383 回答
3

为此有一个库例程,nexttowardf(x, -INFINITY);.

如果您想使用自己的代码执行此操作,您可以本机执行(在 IEEE 754 浮点运算中,无需访问浮点编码或组件),如下所示(在 C 中)。

提供了两种版本,一种在每种情况下都使用次正规值(在某些处理器上可能很慢),另一种仅在输入很小时才使用次正规值(但它有一个分支)。+INFINITY 不支持作为输入,尽管可以通过简单的测试添加支持。这是为 编写的double,但对 的更改float很简单。

如果CompileMain定义了,它还包括一个测试程序。

#include <float.h>
#include <math.h>


/*  Return the next floating-point value before the finite value q.

    This was inspired by Algorithm 3.5 in Siegfried M. Rump, Takeshi Ogita, and
    Shin'ichi Oishi, "Accurate Floating-Point Summation", _Technical Report
    05.12_, Faculty for Information and Communication Sciences, Hamburg
    University of Technology, November 13, 2005.
*/
double NextBefore(double q)
{
    // SmallestPositive is the smallest positive floating-point number.
    static const double SmallestPositive = DBL_EPSILON * DBL_MIN;

    /*  Scale is .625 ULP, so multiplying it by any significand in [1, 2)
        yields something in [.625 ULP, 1.25 ULP].
    */
    static const double Scale = 0.625 * DBL_EPSILON;

#if 0
    /*  This version has a branch but uses subnormal values only if q is so
        small that q * Scale is subnormal.
    */
    double increment = fabs(q)*Scale;

    if (0. == increment)
        return q - SmallestPositive;

    return q - increment;
#else
    /*  This version uses a subnormal, SmallestPositive, in each case.
        This might cause poor performance on some processors.
    */
    return q - fmax(SmallestPositive, fabs(q)*Scale);
#endif
}


#if defined CompileMain


#include <stdio.h>
#include <stdlib.h>


#define NumberOf(a) (sizeof (a) / sizeof *(a))


int main(void)
{
    int status = EXIT_SUCCESS;

    static const struct { double in, out; } cases[] =
    {
        { -INFINITY,                -INFINITY                },
        { -0x1.fffffffffffffp1023,  -INFINITY                },
        { -0x1.ffffffffffffep1023,  -0x1.fffffffffffffp1023  },
        { -0x1.ffffffffffffdp1023,  -0x1.ffffffffffffep1023  },
        { -0x1.ffffffffffffcp1023,  -0x1.ffffffffffffdp1023  },
        { -0x1.0000000000003p1023,  -0x1.0000000000004p1023  },
        { -0x1.0000000000002p1023,  -0x1.0000000000003p1023  },
        { -0x1.0000000000001p1023,  -0x1.0000000000002p1023  },
        { -0x1.0000000000000p1023,  -0x1.0000000000001p1023  },

        { -0x1.fffffffffffffp1022,  -0x1.0000000000000p1023  },

        { -0x1.fffffffffffffp1,     -0x1.0000000000000p2     },
        { -0x1.ffffffffffffep1,     -0x1.fffffffffffffp1     },
        { -0x1.ffffffffffffdp1,     -0x1.ffffffffffffep1     },
        { -0x1.ffffffffffffcp1,     -0x1.ffffffffffffdp1     },
        { -0x1.0000000000003p1,     -0x1.0000000000004p1     },
        { -0x1.0000000000002p1,     -0x1.0000000000003p1     },
        { -0x1.0000000000001p1,     -0x1.0000000000002p1     },
        { -0x1.0000000000000p1,     -0x1.0000000000001p1     },

        { -0x1.fffffffffffffp-1022, -0x1.0000000000000p-1021 },
        { -0x1.ffffffffffffep-1022, -0x1.fffffffffffffp-1022 },
        { -0x1.ffffffffffffdp-1022, -0x1.ffffffffffffep-1022 },
        { -0x1.ffffffffffffcp-1022, -0x1.ffffffffffffdp-1022 },
        { -0x1.0000000000003p-1022, -0x1.0000000000004p-1022 },
        { -0x1.0000000000002p-1022, -0x1.0000000000003p-1022 },
        { -0x1.0000000000001p-1022, -0x1.0000000000002p-1022 },
        { -0x1.0000000000000p-1022, -0x1.0000000000001p-1022 },

        { -0x0.fffffffffffffp-1022, -0x1.0000000000000p-1022 },
        { -0x0.ffffffffffffep-1022, -0x0.fffffffffffffp-1022 },
        { -0x0.ffffffffffffdp-1022, -0x0.ffffffffffffep-1022 },
        { -0x0.ffffffffffffcp-1022, -0x0.ffffffffffffdp-1022 },
        { -0x0.0000000000003p-1022, -0x0.0000000000004p-1022 },
        { -0x0.0000000000002p-1022, -0x0.0000000000003p-1022 },
        { -0x0.0000000000001p-1022, -0x0.0000000000002p-1022 },
        { -0x0.0000000000000p-1022, -0x0.0000000000001p-1022 },

        { +0x1.fffffffffffffp1023,  +0x1.ffffffffffffep1023  },
        { +0x1.ffffffffffffep1023,  +0x1.ffffffffffffdp1023  },
        { +0x1.ffffffffffffdp1023,  +0x1.ffffffffffffcp1023  },
        { +0x1.0000000000004p1023,  +0x1.0000000000003p1023  },
        { +0x1.0000000000003p1023,  +0x1.0000000000002p1023  },
        { +0x1.0000000000002p1023,  +0x1.0000000000001p1023  },
        { +0x1.0000000000001p1023,  +0x1.0000000000000p1023  },

        { +0x1.0000000000000p1023,  +0x1.fffffffffffffp1022  },

        { +0x1.0000000000000p2,     +0x1.fffffffffffffp1     },
        { +0x1.fffffffffffffp1,     +0x1.ffffffffffffep1     },
        { +0x1.ffffffffffffep1,     +0x1.ffffffffffffdp1     },
        { +0x1.ffffffffffffdp1,     +0x1.ffffffffffffcp1     },
        { +0x1.0000000000004p1,     +0x1.0000000000003p1     },
        { +0x1.0000000000003p1,     +0x1.0000000000002p1     },
        { +0x1.0000000000002p1,     +0x1.0000000000001p1     },
        { +0x1.0000000000001p1,     +0x1.0000000000000p1     },

        { +0x1.0000000000000p-1021, +0x1.fffffffffffffp-1022 },
        { +0x1.fffffffffffffp-1022, +0x1.ffffffffffffep-1022 },
        { +0x1.ffffffffffffep-1022, +0x1.ffffffffffffdp-1022 },
        { +0x1.ffffffffffffdp-1022, +0x1.ffffffffffffcp-1022 },
        { +0x1.0000000000004p-1022, +0x1.0000000000003p-1022 },
        { +0x1.0000000000003p-1022, +0x1.0000000000002p-1022 },
        { +0x1.0000000000002p-1022, +0x1.0000000000001p-1022 },
        { +0x1.0000000000001p-1022, +0x1.0000000000000p-1022 },

        { +0x1.0000000000000p-1022, +0x0.fffffffffffffp-1022 },
        { +0x0.fffffffffffffp-1022, +0x0.ffffffffffffep-1022 },
        { +0x0.ffffffffffffep-1022, +0x0.ffffffffffffdp-1022 },
        { +0x0.ffffffffffffdp-1022, +0x0.ffffffffffffcp-1022 },
        { +0x0.0000000000004p-1022, +0x0.0000000000003p-1022 },
        { +0x0.0000000000003p-1022, +0x0.0000000000002p-1022 },
        { +0x0.0000000000002p-1022, +0x0.0000000000001p-1022 },
        { +0x0.0000000000001p-1022, +0x0.0000000000000p-1022 },
    };

    for (int i = 0; i < NumberOf(cases); ++i)
    {
        double in = cases[i].in, expected = cases[i].out;
        double observed = NextBefore(in);
        printf("NextBefore(%a) = %a.\n", in, observed);
        if (! (observed == expected))
        {
            printf("\tError, expected %a.\n", expected);
            status = EXIT_FAILURE;
        }
    }

    return status;
}


#endif  // defined CompileMain
于 2013-01-11T14:16:17.743 回答