Reputation: 52
I was told that avoiding to do equal or not_equal on float/double type in C++.
But there are std::equal_to and std::not_equal_to template functions.
So I am wondering that whether it is reliable to use std::equal_to and std::not_equal_to on float/double in c++?
And I am wondering the implementation of the built-in type: float/double in c++, but I couldn't find their source code. Would you please share me their source code too?
Upvotes: 0
Views: 218
Reputation:
First off, to get that out of the way:
In all implementations of the standard library that I know of, std::equal_to<float/double>
and std::not_equal_to<float/double>
simply invoke ==
and !=
respectively.
That being said:
The advice you got about avoiding the use of ==
and !=
is generally correct, but it is a bit of an oversimplification. Doing an equality or inequality comparison on floating point values is perfectly legal and has a very well defined meaning. However, it is very rarely the correct thing to do.
There's a few technical reasons behind this, but the gist of it is that different sets of operations that mathematically land on the same number often end up on different floating point values. Just changing the order of a series of additions can lead to a different result. So something as simple as a + b == c + d
is going to be inherently unreliable.
If you want to see just how easy it is to mess things up, compile and run the following program:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::setprecision(17) << 0.1 << "\n";
}
Finally, to answer your question as asked: "Where is the implementation?"
In a modern context, on general purpose CPUs that you most likely compile your code for, there is no source code to the implementation for us to point you at. The floating point operations are done directly as cpu-level instructions. If you were dealing with some microcontrollers, old architectures, or other exotic computers, then that would be a different matter.
Upvotes: 5