0

i'm trying to understand why in the following situation i don't get an overflow:

double x = 1.7976931348623157E+308; //this is the max value of double

x = x + 0.5;

When checking the value of x after adding 0.5 i still get the same result.

Anyone?

  • 2
    Although "*double*" the precision ***is*** limited. – alk Jun 15 '16 at 08:38
  • 1
    By the time `0.5` has been aligned for the add, its significance will be lost through shifting the mantissa (to match the exponents), so it will just add `0`. – Weather Vane Jun 15 '16 at 08:46
  • If there are 52 bits in the mantissa, this will happen when the exponents of the two operands differ by more than 52. This is the case for addition or subttraction. When multiplying and dividing, it's a different matter. – Weather Vane Jun 15 '16 at 08:49
  • try reading this http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – terence hill Jun 15 '16 at 08:52
  • When you are a billionaire then inheriting a penny does not make you richer. You would have to write 309 digits to see the result of that expression. The *double* type can only store 15 significant digits. – Hans Passant Jun 15 '16 at 09:16

2 Answers2

0

Generally if you want to add a value to a double x the added value should be within the precision range for it to change the value at all.

For a double you get a precision of ~16 digits. So, if the added value is less than (x/1E+16), then there will be no change in the result.

With a little trial and error, in your case, adding a value of 1E+292, to the given double, gives a result of +INF.

double x = 1.7976931348623157E+308; //this is the max value of double

x = x + 1E+292;
printf ("\nx = %lf",x);

Result

x = 1.#INF00

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
0

Consider the analogy with exponent notation.

Suppose you are allowed 4 significant digits, so the number 1234000.0 will be represented by 1.234e6.

Now try adding 0.5 which should be 1234000.5.

Even if the intermediate buffer is big enough to hold that significance, its representation within the proscribed limit is still 1.234e6.

But if the intermediate buffer can hold, say, only 7 digits, the aligned values to add are

1234000
      0
-------
1234000

so the 0.5 loses its significance even before the addition is performed. In the case of double you can be quite sure the intermediate buffer cannot hold 308 digits equivalent.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56