So, today I've got a bit more theoretical question. While studying the floating point types I have written a little test:
#include <iostream>
int main()
{
float floatTest = 10.0 / 3.0;
double doubleTest = 10.0 / 3.0;
const long long ex = 100000000000;
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout << "float test: " << floatTest * ex << std::endl;
std::cout << "double test: " << doubleTest * ex << std::endl << std::endl;
return 0;
}
Results are not really what I expected:
Now, I know that floating point numbers are made from mantissa and exponent, so it would be natural for me that in case of the float
type, which by standard guarantees precision up to 7 digits mantissa would be something like 3.333333
and the exponent's value would for example be 37
, so I have basically no idea where are these random trash digits coming from. I have also observed one other thing. While there are plenty of these random digits after float
loses precision, there is only one random digit after double
loss of precision. That's quite weird in my opinion.
Now the question:
Same as in the title, why are there random trash digits in floating point numbers? Is C++ trying to somehow compute the further part of this repeating decimal or is it just the issue with mantissa or is it something else?
I'm literally clueless, where to look for the proper answer. Only thing I have found is IEEE 754 standard, but AFAIK I'd need to buy it if I'd like to read it.