1

I have a problem with summing two doubles

double a = 1e+020;
double b = -4000;
double res = a + b; //result = 1e+020

Why res is equal to a?

ks1322
  • 33,961
  • 14
  • 109
  • 164
Simon I
  • 13
  • 2
  • 2
    how do you display the result? – DipStax Oct 14 '20 at 08:37
  • 1
    because the -4000 become insignificant for scientific notation. – Raildex Oct 14 '20 at 08:39
  • Because floating point numbers store only limited number of leading digits – fas Oct 14 '20 at 08:39
  • 1
    `1e+020` is a very large number, and `4000` is a very small number. Subtracting `4000` from `1e+020` will make almost no difference. – Some programmer dude Oct 14 '20 at 08:39
  • Consider that on most systems, you only have 64 bits to work with here and numbers that go as high as ~1e308 as well as including non-integers. A 64-bit integer type only goes up to ~10^19. – chris Oct 14 '20 at 08:42
  • @chris the issue here is not magnitude but precision (refering to 1e308 is misleading) – 463035818_is_not_an_ai Oct 14 '20 at 08:49
  • @idclev463035818, My comment is about precision. There's a huge range to cover (which is what I was trying to demonstrate) and only 64 bits to do it. – chris Oct 14 '20 at 08:56
  • @chris but range and precision are not directly related because seperate bits are used for the exponent – 463035818_is_not_an_ai Oct 14 '20 at 08:57
  • @idclev463035818, I think that's beside the point I was trying to make. It's confusing to a lot of people why not every integer is representable and I was trying to give some high-level intuition for _why_ so many numbers are unrepresentable. Not so much _which_ numbers, but the idea that you can pick whatever bit representation you want and it won't come anywhere close to having everything. – chris Oct 14 '20 at 09:04

1 Answers1

1

double has not infinite number of significant digits. You can query number of digits in base 10 with std::numeric_limits:

#include <iostream>
#include <limits>

int main(){
    std::cout << std::numeric_limits<double>::digits10;
}

Typical output is

15

but you are requesting 16 significant digits.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185