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
  • 17,472
  • 10
  • 53
  • 96
srip
  • 525
  • 1
  • 5
  • 17

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
  • 235,058
  • 25
  • 372
  • 444
Sam Varshavchik
  • 98,597
  • 5
  • 74
  • 125
  • @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