0

I have a long double variable and I noticed that for really big numbers I get a numeric error. Small reproducible example:

#include <iostream>

using namespace std;

int main()
{
    std::cout.precision(64);
    long double value = 45;
    long double d = 39353425746711768;
    long double factor = 622;
    value += (d * factor);
    std::cout << value << std::endl;
    return 0;
}

I get the following result:

24477830814454719740

But:

45 + 39353425746711768 * 622 = 24477830814454719741

How can I get 24477830814454719741? Does there any hidden conversions being made by CPP?

vesii
  • 2,760
  • 4
  • 25
  • 71
  • Floating point math is inherently not mathematical exact when compared to the real numbers. See duplicate. If you require exact integers, use an integer type, not a floating point type. If the largest integer type is too small to hold your values, you need an arbitrary-length integer library. – user17732522 Jun 16 '22 at 19:36
  • 1
    It just happens that `24477830814454719741` can't be exactly represented by a `long double` in your system. You'd need just *one* extra bit of precision. See e.g. https://godbolt.org/z/sYz97e3cv – Bob__ Jun 16 '22 at 20:10

0 Answers0