การเปรียบเทียบ floating-point ด้วย == ไม่เชื่อถือได้ เพราะ precision error ควรใช้ epsilon comparison
ฟังก์ชันเปรียบเทียบแบบง่าย
#include <iostream>
#include <cmath>
using namespace std;
#define EPSILON 0.000001
bool areSame(double a, double b) {
return fabs(a - b) < EPSILON;
}
int main() {
double a = 1.005, b = 1.006;
cout << areSame(a, a); // 1 (true)
cout << areSame(a, b); // 0 (false)
}
ผลลัพธ์
1 0
ตรวจสอบว่า |a-b| < epsilon (ค่าความคลาดเคลื่อมที่ยอมรับได้)
สำหรับความแม่นยำสูง: อ่าน Comparing Floating Point Numbers (Bruce Dawson) - ครอบคลุม ULP comparison, relative error, special cases (NaN, infinity, denormals)