先澄清一个概念,浮点数并不一定等于小数,定点数也并不一定就是整数。所谓浮点数就是小数点在逻辑上是不固定的,而定点数只能表示小数点固定的数值,具用浮点数或定点数表示某哪一种数要看用户赋予了这个数的意义是什么。
C++中的浮点数有6种,分别是:
float:单精度,32位
unsigned float:单精度无符号,32位
double:双精度,64位
long double:高双精度,80位
在采用C++编写算法时,经常需要判断两个浮点数是否相等。由于计算精度的原因,采用“==”运算符是不可行的。下面给出采用C++11标准判断两个浮点数是否相等的代码:
// Test whether two float or double numbers are equal.
// ulp: units in the last place.
template <typename T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
IsAlmostEqual(T x, T y, int ulp = 2) {
// the machine epsilon has to be scaled to the magnitude of the values used
// and multiplied by the desired precision in ULPs (units in the last place)
return std::fabs(x - y) <
std::numeric_limits<T>::epsilon() * std::fabs(x + y) * ulp
// unless the result is subnormal
|| std::fabs(x - y) < std::numeric_limits<T>::min();
}
上述代码中,std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type的含义是:如果数据类型T不是整数类型,则返回值类型为bool,否则会导致编译错误。也就是说,只允许进行非整数数值类型的比较。当然这里有个隐含前提,T必须是数值类型,不可能拿一个类似于Person的类型去实例化该函数,如果这样做,则std::numeric_limits<T>肯定通不过,会报编译错误。
下面是示例代码:
#include <cmath>
#include <limits>
#include <iostream>
#include <type_traits>
// Test whether two float or double numbers are equal.
// ulp: units in the last place.
template <typename T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
IsAlmostEqual(T x, T y, int ulp = 2)
{
// the machine epsilon has to be scaled to the magnitude of the values used
// and multiplied by the desired precision in ULPs (units in the last place)
return std::fabs(x - y) < std::numeric_limits<T>::epsilon() * std::fabs(x + y) * ulp
// unless the result is subnormal
|| std::fabs(x - y) < std::numeric_limits<T>::min();
}
int main()
{
double d1 = 0.2;
double d2 = 1 / std::sqrt(5) / std::sqrt(5);
std::cout << "d1 = " << d1 << std::endl;
std::cout << "d2 = " << d2 << std::endl;
if (d1 == d2)
{
std::cout << "d1 == d2" << std::endl;
}
else
{
std::cout << "d1 != d2" << std::endl;
}
if (IsAlmostEqual(d1, d2))
{
std::cout << "d1 almost equals d2" << std::endl;
}
else
{
std::cout << "d1 does not almost equal d2" << std::endl;
}
return 0;
}
d1 = 0.2
d2 = 0.2
d1 != d2
d1 almost equals d2
long:
两个Long类型的数据A和B,在判断A和B是否相等的时候需要看A和B的范围,根据源码可知,当A和B的数值在[-128--127]之间的时候用==判断即可,但是超过范围的时候会new一个新的实体,这时要判断是否相等需要转换为A.longValue()和B.longValue(),然后用==判断。
原来是因为Long中有一个静态的内部类LongCache,专门用于缓存-128至127之间的值,一共256个元素。
如果仅仅是缓存下来而不去使用那么就没有任何意义。valueOf(long l)就是使缓存派上用场的方法,它会判断传入的参数是否在-128-127之间,如果是则直接从缓存中返回对应的引用,否则新创建一个Long的实例。
使用equals
Long重写了equals方法,如下:
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
它是先通过.longValue()
方法获取Long对象的基本类型long的值之后再做比较的。
但是我们用longValue比较时容易忘记后面一个包装类调longValue方法
所以,最好还是使用equals
进行比较。也可以直接用.longValue()比较