I wanted to calculate the machine Epsilon, the smallest possible number e
that gives 1 + e > 1
using different data types of C++: float
, double
and long double
.
Here's my code:
#include <cstdio>
template<typename T>
T machineeps() {
T epsilon = 1;
T expression;
do {
epsilon = epsilon / 2;
expression = 1 + epsilon;
} while(expression > 1);
return epsilon;
}
int main() {
auto epsf = machineeps<float>();
auto epsd = machineeps<double>();
auto epsld = machineeps<long double>();
std::printf("epsilon float: %22.17e\nepsilon double: %22.17e\nepsilon long double: %Le\n", epsf, epsd, epsld);
return 0;
}
But I get this strange output:
epsilon float: 5.96046447753906250e-008
epsilon double: 1.11022302462515650e-016
epsilon long double: -0.000000e+000
The values for float
and double
are what I was expecting, but, I cannot explain the long double
behavior.
Can somebody tell me what went wrong?