The first expression (namely (exp(M_PI) - M_PI)
) is a double
, the second expression (namely a
) is a float
. Neither even have 20 decimal digits of precision, but the float
has a lot less precision than the double
.
Same floating point operation, different results
-
23-06-2022 - |
Question
I really can't wrap my head around the fact that this code gives 2 results for the same formula:
#include <iostream>
#include <cmath>
int main() {
// std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(20);
float a = (exp(M_PI) - M_PI);
std::cout << (exp(M_PI) - M_PI) << "\n";
std::cout << a << "\n";
return (0);
}
I don't really think that the IEEE 754 floating point representation is playing a significant role here ...
Solution
OTHER TIPS
Because M_PI
are of type double
, so change a
to double
, you will have the same result:
#include <iostream>
#include <cmath>
int main() {
// std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout.precision(20);
double a = (exp(M_PI) - M_PI);
std::cout << (exp(M_PI) - M_PI) << "\n";
std::cout << a << "\n";
return (0);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow