C++03中最接近浮点数的整数

13
对于某个整数类型,即使浮点数值远超出整数可表示范围,我该如何找到最靠近某个浮点数值的整数值?
更准确地说:
设 F 是一个浮点类型(可能是 float、double 或 long double)。设 I 是一个整数类型。
假设 F 和 I 都有 std::numeric_limits<> 的有效特化。
给定一个可表示的 F 值,并且只使用 C++03,我该如何找到最接近的可表示 I 值?
我需要一个纯粹、高效和线程安全的解决方案,并且假设平台除了 C++03 保证的东西之外什么也不知道。
如果不存在这样的解决方案,是否可以使用 C99/C++11 的新功能找到一个解决方案?
使用 C99 的 lround() 似乎存在问题,因为它报告定义域错误的方式比较复杂。这些定义域错误能以一种便携和线程安全的方式捕获吗?
注:我知道 Boost 可能通过其 boost::numerics::converter<> 模板提供解决方案,但由于其高度复杂和冗长,我无法从中提取要点,因此我无法确定他们的解决方案是否假定了 C++03 之外的内容。
以下天真的方法失败了,因为当 f 的整数部分不是 I 的可表示值时,I(f) 的结果在 C++03 中是未定义的。
template<class I, class F> I closest_int(F f)
{
  return I(f);
}

考虑以下方法:

template<class I, class F> I closest_int(F f)
{
  if (f < std::numeric_limits<I>::min()) return std::numeric_limits<I>::min();
  if (std::numeric_limits<I>::max() < f) return std::numeric_limits<I>::max();
  return I(f);
}

由于F(std::numeric_limits<I>::min())F(std::numeric_limits<I>::max())的整数部分可能仍然无法在I中表示,因此这也会失败。

最后考虑这第三种方法,它也会失败:

template<class I, class F> I closest_int(F f)
{
  if (f <= std::numeric_limits<I>::min()) return std::numeric_limits<I>::min();
  if (std::numeric_limits<I>::max() <= f) return std::numeric_limits<I>::max();
  return I(f);
}

这次 I(f) 总是有一个明确定义的结果,然而,由于 F(std::numeric_limits<I>::max()) 可能比 std::numeric_limits<I>::max() 小得多,因此可能会返回一个整数值低于 std::numeric_limits<I>::max() 的浮点值的 std::numeric_limits<I>::max()

请注意,所有的麻烦都是因为不确定转换 F(i) 是否向最接近的可表示浮点值上舍入或下舍入。

以下是C++03的相关章节(4.9 浮点-整数转换):

整数类型或枚举类型的右值可以转换为浮点类型的右值。如果可能的话结果是精确的。否则,它是实现定义的选择,要么是下一个更低的可表示值,要么是更高的可表示值。


1
写得很好的问题。我希望所有问题都能像这样。 - Robert Harvey
@AlexeyFrunze 我想要将 'float -> int',但是在我脆弱的尝试中,我将最大和最小整数转换为浮点数,引用是为了阐明后者转换为相反方向。我会尝试进行编辑,使其更加清晰明了。 - Kristian Spangsege
@AlexeyFrunze 你又删掉了你的问题吗?还是我搞错了什么? - Kristian Spangsege
抱歉,我在理解问题后删除了评论。 - Alexey Frunze
我知道这并不是你问题的核心,但如果你想要最接近的整数而不是被截断的整数部分,你不应该使用I(f+0.5)吗? - Vaughn Cato
@VaughnCato 我猜,+.5 可以很容易地插入:f += (f >= 0) ? +0.5 : -0.5; - Alexey Frunze
1个回答

3
我有一个实用的解决方案,适用于基数2(二进制)浮点类型和长度为64位及更长的整数类型。请见下面。注释应该很清楚。输出如下。
// file: f2i.cpp
//
// compiled with MinGW x86 (gcc version 4.6.2) as:
//   g++ -Wall -O2 -std=c++03 f2i.cpp -o f2i.exe
#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

template<class I, class F> I truncAndCap(F f)
{
/*
  This function converts (by truncating the
  fractional part) the floating-point value f (of type F)
  into an integer value (of type I), avoiding undefined
  behavior by returning std::numeric_limits<I>::min() and
  std::numeric_limits<I>::max() when f is too small or
  too big to be converted to type I directly.

  2 problems:
  - F may fail to convert to I,
    which is undefined behavior and we want to avoid that.
  - I may not convert exactly into F
    - Direct I & F comparison fails because of I to F promotion,
      which can be inexact.

  This solution is for the most practical case when I and F
  are radix-2 (binary) integer and floating-point types.
*/
  int Idigits = numeric_limits<I>::digits;
  int Isigned = numeric_limits<I>::is_signed;

/*
  Calculate cutOffMax = 2 ^ std::numeric_limits<I>::digits
  (where ^ denotes exponentiation) as a value of type F.

  We assume that F is a radix-2 (binary) floating-point type AND
  it has a big enough exponent part to hold the value of
  std::numeric_limits<I>::digits.

  FLT_MAX_10_EXP/DBL_MAX_10_EXP/LDBL_MAX_10_EXP >= 37
  (guaranteed per C++ standard from 2003/C standard from 1999)
  corresponds to log2(1e37) ~= 122, so the type I can contain
  up to 122 bits. In practice, integers longer than 64 bits
  are extremely rare (if existent at all), especially on old systems
  of the 2003 C++ standard's time.
*/
  const F cutOffMax = F(I(1) << Idigits / 2) * F(I(1) << (Idigits / 2 + Idigits % 2));

  if (f >= cutOffMax)
    return numeric_limits<I>::max();

/*
  Calculate cutOffMin = - 2 ^ std::numeric_limits<I>::digits
  (where ^ denotes exponentiation) as a value of type F for
  signed I's OR cutOffMin = 0 for unsigned I's in a similar fashion.
*/
  const F cutOffMin = Isigned ? -F(I(1) << Idigits / 2) * F(I(1) << (Idigits / 2 + Idigits % 2)) : 0;

  if (f <= cutOffMin)
    return numeric_limits<I>::min();

/*
  Mathematically, we may still have a little problem (2 cases):
    cutOffMin < f < std::numeric_limits<I>::min()
    srd::numeric_limits<I>::max() < f < cutOffMax

  These cases are only possible when f isn't a whole number, when
  it's either std::numeric_limits<I>::min() - value in the range (0,1)
  or std::numeric_limits<I>::max() + value in the range (0,1).

  We can ignore this altogether because converting f to type I is
  guaranteed to truncate the fractional part off, and therefore
  I(f) will always be in the range
  [std::numeric_limits<I>::min(), std::numeric_limits<I>::max()].
*/

  return I(f);
}

template<class I, class F> void test(const char* msg, F f)
{
  I i = truncAndCap<I,F>(f);
  cout <<
    msg <<
    setiosflags(ios_base::showpos) <<
    setw(14) << setprecision(12) <<
    f << " -> " <<
    i <<
    resetiosflags(ios_base::showpos) <<
    endl;
}

#define TEST(I,F,VAL) \
  test<I,F>(#F " -> " #I ": ", VAL);

int main()
{
  TEST(short, float,     -1.75f);
  TEST(short, float,     -1.25f);
  TEST(short, float,     +0.00f);
  TEST(short, float,     +1.25f);
  TEST(short, float,     +1.75f);

  TEST(short, float, -32769.00f);
  TEST(short, float, -32768.50f);
  TEST(short, float, -32768.00f);
  TEST(short, float, -32767.75f);
  TEST(short, float, -32767.25f);
  TEST(short, float, -32767.00f);
  TEST(short, float, -32766.00f);
  TEST(short, float, +32766.00f);
  TEST(short, float, +32767.00f);
  TEST(short, float, +32767.25f);
  TEST(short, float, +32767.75f);
  TEST(short, float, +32768.00f);
  TEST(short, float, +32768.50f);
  TEST(short, float, +32769.00f);

  TEST(int, float, -2147483904.00f);
  TEST(int, float, -2147483648.00f);
  TEST(int, float, -16777218.00f);
  TEST(int, float, -16777216.00f);
  TEST(int, float, -16777215.00f);
  TEST(int, float, +16777215.00f);
  TEST(int, float, +16777216.00f);
  TEST(int, float, +16777218.00f);
  TEST(int, float, +2147483648.00f);
  TEST(int, float, +2147483904.00f);

  TEST(int, double, -2147483649.00);
  TEST(int, double, -2147483648.00);
  TEST(int, double, -2147483647.75);
  TEST(int, double, -2147483647.25);
  TEST(int, double, -2147483647.00);
  TEST(int, double, +2147483647.00);
  TEST(int, double, +2147483647.25);
  TEST(int, double, +2147483647.75);
  TEST(int, double, +2147483648.00);
  TEST(int, double, +2147483649.00);

  TEST(unsigned, double,          -1.00);
  TEST(unsigned, double,          +1.00);
  TEST(unsigned, double, +4294967295.00);
  TEST(unsigned, double, +4294967295.25);
  TEST(unsigned, double, +4294967295.75);
  TEST(unsigned, double, +4294967296.00);
  TEST(unsigned, double, +4294967297.00);

  return 0;
}

输出结果(ideone 的打印结果与我的电脑相同):

float -> short:          -1.75 -> -1
float -> short:          -1.25 -> -1
float -> short:             +0 -> +0
float -> short:          +1.25 -> +1
float -> short:          +1.75 -> +1
float -> short:         -32769 -> -32768
float -> short:       -32768.5 -> -32768
float -> short:         -32768 -> -32768
float -> short:      -32767.75 -> -32767
float -> short:      -32767.25 -> -32767
float -> short:         -32767 -> -32767
float -> short:         -32766 -> -32766
float -> short:         +32766 -> +32766
float -> short:         +32767 -> +32767
float -> short:      +32767.25 -> +32767
float -> short:      +32767.75 -> +32767
float -> short:         +32768 -> +32767
float -> short:       +32768.5 -> +32767
float -> short:         +32769 -> +32767
float -> int:    -2147483904 -> -2147483648
float -> int:    -2147483648 -> -2147483648
float -> int:      -16777218 -> -16777218
float -> int:      -16777216 -> -16777216
float -> int:      -16777215 -> -16777215
float -> int:      +16777215 -> +16777215
float -> int:      +16777216 -> +16777216
float -> int:      +16777218 -> +16777218
float -> int:    +2147483648 -> +2147483647
float -> int:    +2147483904 -> +2147483647
double -> int:    -2147483649 -> -2147483648
double -> int:    -2147483648 -> -2147483648
double -> int: -2147483647.75 -> -2147483647
double -> int: -2147483647.25 -> -2147483647
double -> int:    -2147483647 -> -2147483647
double -> int:    +2147483647 -> +2147483647
double -> int: +2147483647.25 -> +2147483647
double -> int: +2147483647.75 -> +2147483647
double -> int:    +2147483648 -> +2147483647
double -> int:    +2147483649 -> +2147483647
double -> unsigned:             -1 -> 0
double -> unsigned:             +1 -> 1
double -> unsigned:    +4294967295 -> 4294967295
double -> unsigned: +4294967295.25 -> 4294967295
double -> unsigned: +4294967295.75 -> 4294967295
double -> unsigned:    +4294967296 -> 4294967295
double -> unsigned:    +4294967297 -> 4294967295

我撤回之前的评论。汇编输出看起来合理。一开始编译器将truncAndCap()的调用内联,这就是为什么我在转换代码附近看到了很多与std::cout相关的无关内容。添加-fno-inline后可以看到truncAndCap()很短。 - Alexey Frunze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接