0
using namespace std;
int main()
{
    float f1 = 5488955, f2 = 0.2197265620, f3 = 0;
    f3 = f1 + f2;
    f3 = f3 - f1;
    cout << f3<<endl;
    return 0;
}

why f3 value getting printed as 0 but not 0.2197265620

shaik reyan
  • 129
  • 1
  • 8
  • Looks like normal floating point round off inaccuracy to me. Add a large number to a small and subtract. When it is renormalized each step, I bet it loses the small decimal part. – Michael Dorgan Aug 18 '20 at 22:26
  • C++ `float` is only guaranteed to have 6 significant digits, I believe. So at least `548895x` can be accurately stored (the `x` could be any number). The rest gets truncated. – cdhowie Aug 18 '20 at 22:29
  • Adding a count after the first `f3` assign will show you that f3 already has lost the decimal portion at that point... – Michael Dorgan Aug 18 '20 at 22:30

2 Answers2

5

The IEEE-754 floating point format has limited precision. Double-precision floating point numbers have more precision than single-precision floating point numbers, as they use 64 bits instead of only 32 bits.

The floating-point number 5488955.2 cannot be represented in a single-precision floating point number. The closest numbers it can represent are 5488955.0 and 5488955.5. It is therefore rounded down to 5488955.0. In order to prevent this rounding, you must use double-precision floating point numbers, by using the data type double instead of float.

However, with very high numbers, you will sooner or later have the same problem with double. Therefore, if you require arbitrary precision, you cannot use float or double, but must use a special arbitrary precision software library. But for most cases, double should be sufficient.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • It took me by surprise just how low `float` precision is. `5488955` requires 23 bits to be represented. The sign bit and biased exponent are 9 bits and thus no more decimals can be appended. – Jan Schultke Aug 18 '20 at 22:34
1

Consider switching to doubles. If you change the float to a double it would work. In C++ I recommend using doubles because in some cases floats are broken.

DedS3t
  • 183
  • 1
  • 7
  • 3
    floats are not broken. They use lets bits to store data than doubles and thus can contain less precision. Often this is ok and even better (speed!), so saying they are broken is a great overstatement. – Michael Dorgan Aug 18 '20 at 22:31
  • 1
    Doubles have the same issue as floats, it would just take larger differences in magnitude to be noticeable. – interjay Aug 18 '20 at 22:35