计算机中的浮点数 - 关于浮点数的编程需要注意什么
flyfish
其他部分请看
计算机中的浮点数 - 为什么十进制的 0.1 在计算机中是一个无限循环小数
计算机中的浮点数 - 二进制和十进制之间转换
在使用浮点数编程时会检查浮点数的范围, 直接比较可能失败,则会使用 epsilon 进行比较;检查特殊值等。
#include <iostream>
#include <cmath>
#include <limits>
int main() {
//检查浮点数的范围
double maxDouble = std::numeric_limits<double>::max();
double minDouble = std::numeric_limits<double>::min();
std::cout << "maxDouble" << maxDouble<<std::endl;
std::cout << "minDouble:" << minDouble<<std::endl;
double a = 0.1;
double b = 0.2;
double c = 0.3;
// 直接比较可能失败
if (a + b == c) {
std::cout << "a + b == c" << std::endl;
} else {
std::cout << "a + b != c" << std::endl;
}
// 使用 epsilon 进行比较
const double epsilon = 1e-9;
if (fabs((a + b) - c) < epsilon) {
std::cout << "a + b is approximately equal to c" << std::endl;
} else {
std::cout << "a + b is not approximately equal to c" << std::endl;
}
// 检查特殊值
double d = 0.0;
double e = 1.0 / d; // Infinity
double f = 0.0 / d; // NaN
if (std::isinf(e)) {
std::cout << "e is Infinity" << std::endl;
}
if (std::isnan(f)) {
std::cout << "f is NaN" << std::endl;
}
return 0;
}
maxDouble1.79769e+308
minDouble:2.22507e-308
a + b != c
a + b is approximately equal to c
e is Infinity
f is NaN
区分正无穷和负无穷
#include <iostream>
#include <limits>
#include <cmath>
int main() {
// 创建正无穷和负无穷
double pos_inf = std::numeric_limits<double>::infinity();
double neg_inf = -std::numeric_limits<double>::infinity();
// 检查 pos_inf 是否为无穷
if (std::isinf(pos_inf)) {
if (pos_inf > 0) {
std::cout << "pos_inf is positive infinity." << std::endl;
} else {
std::cout << "pos_inf is negative infinity." << std::endl;
}
} else {
std::cout << "pos_inf is not infinity." << std::endl;
}
// 检查 neg_inf 是否为无穷
if (std::isinf(neg_inf)) {
if (neg_inf > 0) {
std::cout << "neg_inf is positive infinity." << std::endl;
} else {
std::cout << "neg_inf is negative infinity." << std::endl;
}
} else {
std::cout << "neg_inf is not infinity." << std::endl;
}
// 测试其他例子
double a = 1.0 / 0.0; // 正无穷
double b = -1.0 / 0.0; // 负无穷
if (std::isinf(a)) {
if (a > 0) {
std::cout << "a is positive infinity." << std::endl;
} else {
std::cout << "a is negative infinity." << std::endl;
}
} else {
std::cout << "a is not infinity." << std::endl;
}
if (std::isinf(b)) {
if (b > 0) {
std::cout << "b is positive infinity." << std::endl;
} else {
std::cout << "b is negative infinity." << std::endl;
}
} else {
std::cout << "b is not infinity." << std::endl;
}
return 0;
}
pos_inf is positive infinity.
neg_inf is negative infinity.
a is positive infinity.
b is negative infinity.