Skip to content

Floating point value equality with integral

An answer to this question on Stack Overflow.

Question

This issue fundementally comes down to 2 lines, the 1st line will output 1.

std::cout << sqrt(pow(b->x - a->x, 2) + pow(b->y - a->y, 2) + pow(b->z - a->z, 2)) << std::endl;

Yet the 2nd line will output 0, how is this possible?

std::cout << (sqrt(pow(b->x - a->x, 2) + pow(b->y - a->y, 2) + pow(b->z - a->z, 2)) == 1) << std::endl;

Minimal complete verifiable example:

struct vertice {
	double x, y, z;
	vertice(double x, double y, double z) {
		this->x = x;
		this->y = y;
		this->z = z;
	}
};
void cartDistance(const vertice * a, const vertice * b);
int main() {
	cartDistance(new vertice(0, 0, 0), new vertice(0, 0, 1));
	system("pause");
	return 0;
}
void cartDistance(const vertice * a, const vertice * b) {
	std::cout << "dist: " << sqrt(pow(b->x - a->x, 2) + pow(b->y - a->y, 2) + pow(b->z - a->z, 2)) << std::endl;
	std::cout << "dist check: " << (sqrt(pow(b->x - a->x, 2) + pow(b->y - a->y, 2) + pow(b->z - a->z, 2)) == 1) << std::endl;
}

Answer

The stream output operator is rounding because you don't really want to see 0.999999999999999999997. The math is inexact, and that is being hidden from you. The comparison operator does care about this, though.

Floating point operations require care.

Using std::setprecision () will allow you to see more digits after the decimal, at which point your problem will be more obvious.