numeric_limits

numeric_limits <int>

我们常讲,int:是有符号整型,而 unsigned int:是无符号整型,可此话怎讲呢,自然是值域(range),也即数值范围不同。

std::cout << std::numeric_limits <unsigned int>::min() << std::endl;
                                // 0
std::cout << std::numeric_limits<unsigned int>::max() << std::endl;
                        // 4294967295
                        // 4294967295的二进制恰为:
                        // 1111 1111 1111 1111 1111 1111 1111 1111 == 2^32-1                    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

也即 unsigned int 的取值范围为:[0,2321][0,232−1]

我们再来看 int的取值范围(最高位,也即第32位为符号位):

std::cout << std::numeric_limits<int>::min() << std::endl;
                        // -2147483648
                        // 也即2^31,第32位为1,其余各位均为0
std::cout << std::numeric_limits<int>::max() << std::endl;
                        // 22147483647
                        // 2^31-1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

故 int 的取值范围为:[2047483648,2047483647][−2047483648,2047483647]

numeric_limits <double>

std::cout << std::numeric_limits<double>::min() << std::endl;
                            // 2.22507e-308
std::cout << std::numeric_limits<double>::max() << std::endl;
                            // 1.79769e+308
  • 1
  • 2
  • 3
  • 4

注意这里的 std::numeric_limits<double>::min() 表达不是 −∞,而是(正)无穷小量 ϵϵ

如果我们想要表达负无穷(−∞),我们自然可以使用:

std::cout << -std::numeric_limits<double>::max() << std::endl;
                            // -1.79769e+308
  • 1
  • 2
  • 3

std::numeric_limits<T>::epsilon()

注意这里:

std::cout << std::numeric_limits<double>::min() << std::endl;
                            // 2.22507e-308
std::cout << std::numeric_limits<double>::epsilon() << std::endl;
                            // 2.22045e-016
  • 1
  • 2
  • 3
  • 4

两者显然不在一个数量级上。 
我们来看 msdn 对epsilon的说明:

The function returns the difference between 1 and the smallest value greater than 1 that is representable for the data type.

也即 std::numeric_limits<T>::epsilon() 返回的是计算机体系结构所能判断的两个同类型的数据是否相等的极限,也即如果两个数的差值小于std::numeric_limits<T>::epsilon() ,在计算机看来两者没差。

std::cout << std::boolalpha;
std::cout << (1. == 1.+std::numeric_limits<double>::epsilon()) << std::endl;
                                // false
std::cout << (1. == 1.+std::numeric_limits<double>::epsilon()/2) << std::endl;
                                // true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

应用

用最大值(max,取值范围的极限)表示该值未取值

#define NULL_INT std::numeric_limits<int>::max()
#define NULL_SIZE std::numeric_limits<unsigned int>::max()
#define NULL_REAL std::numeric_limits<double>::max()

猜你喜欢

转载自blog.csdn.net/qq_40213457/article/details/81053321
今日推荐