Comparing float and double in C++: How to avoid errors due to precision loss?
Hi everyone. I'm a beginner C++ developer and I've encountered a problem when comparing floating-point numbers. I'm writing a program for simulating physical processes, and I need to check whether two numbers of type float or double are equal.
The problem is that due to calculation errors (for example, 0.1 + 0.2 does not equal 0.3), direct comparison using `==` almost never works:
```cpp
#include
int main() {
double a = 0.1 + 0.2;
double b = 0.3;
if (a == b) {
std::cout << "Equal" << std::endl;
} else {
std::cout << "Not equal" << std::endl; // This is printed
}
return 0;
}
```
I've read that you need to compare with some "epsilon" (tolerance), but I don't understand how to choose this value correctly. For example, for some numbers `1e-6` works, but for