1

I have something like

double d1=4.0;
double d2=8.0;

I am trying to print sum of those double values using cout. Is it possible to print the sum with exact precision without setting the precision?

If the values are

double d1=4.23;
double d2=4.0;

The sum should print 8.23 without any additional zeros.

Ajay
  • 18,086
  • 12
  • 59
  • 105
srip
  • 617
  • 1
  • 6
  • 18

1 Answers1

3

Native floating values do not work this way.

As soon as you set a double:

double d1=4.23;

Then the actual value that d gets set to is, approximately, 4.2300000000000004263256

This happens right off the bat. Do not pass Go. Do not collect $200. It's too late, even before you compute the sum, because 4.23 is not a representable number in base 2 floating point representation.

The only way to achieve exact precision non-integer math is to use a library that's specially designed for this purpose, such as GMP's mpq_t rational numbers.

user2357112
  • 260,549
  • 28
  • 431
  • 505
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • @FirstStep - thanks for pointing out my typo; I actually ran a quick test, rather than compute this myself, and fat-fingered everything... But the basic point is still true. – Sam Varshavchik Jun 09 '16 at 17:27