I'm not a C++ programmer, I'm of the Java variety, but I know that this is expected behaviour.
Float has quite a low precision (4 bytes in Java) so you get results like this:-
https://lists.xcf.berkeley.edu/lists/advanced-java/2002-January/018167.html
Consider using the 'double' type instead (I assume it is the same as in Java) which uses 8 bytes.
It's all to do with the intricacies (inaccuracies) of storing floating point values in binary.
Matt
On Saturday 30 Oct 2004 13:44, Stuart Bailey wrote:
Hi, I'm trying to investigate a weird mathematical problem I've come across using G++. I only have G++ on SuSE 9.1, and so I'm unable to test the code on other systems, kernels etc. I would be grateful if someone could compile and run this code and let me have the results:
#include <iostream> #include <math.h>
int main() { float l = 45.4567; float d = floorf(l); float m = floorf((l - d) * 60.); float s = (((l - d) * 60.) - m) * 60.;
std::cout << "l = " << l << std::endl; std::cout << "d = " << d << std::endl; std::cout << "l-d = " << l - d << std::endl; std::cout << "(l-d) * 60.0 = " << (l - d) * 60. << std::endl; std::cout << "m = " << m << std::endl; std::cout << "s = " << s << std::endl;
float r = (s / 3600.) + (m / 60.) + d; std::cout << "reconstructed= " << r << std::endl;
return 0; }
Basically, I getting an odd value printed for l - d (it comes out as 0.456699 and not 0.4567 as expected).
Many thanks,
Stuart.