double type variables

Hi,

Please check following code:

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <iomanip>

int main(int argc, char *argv[])
{
  double someVal = 6.6f;
  std::cout << std::fixed << std::setprecision (9) << someVal << "\n";
  return 0;
}


shows output as:

6.599999905


Can somebody kindly explain why does this happen?

Thank you.

Best Regards
Rupesh
Many floating point values are approximations and can't be stored exactly. float has lower precision than double so if you change
double someVal = 6.6f;
to
double someVal = 6.6;
you will probably get the correct output. Note that someVal is probably still an approximation of 6.6.
Last edited on
This has to do with how numbers are encoded, with an emphasis for performance, as long as the accuracy is "good enough".

http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
http://www.cplusplus.com/forum/articles/3827/

basically, you can't represent floating point numbers very well in binary, there has to be some rounding, that is the result of the rounding.
Topic archived. No new replies allowed.