Search code examples
c++double

Why C++ double giving wrong answer for Just 17 DIGITS?


Recently while practicing I found this problem, Please run this code in your local machine.

#include <bits/stdc++.h>
using namespace std;
double power(double a, double b) {
    double ans = 1;
    for(int i = 1; i <= b; i++){
        ans *= a;
    }
    return ans;
}

int main()
{
    double anaconda = 0;
    for(int i = 0; i < 25; i++){
        anaconda += power(10,i);
        cout << setprecision(30) << fixed <<i << " "<< anaconda << endl;
    }
}

If you run this code you should see something like this

output

Your can also see this code running in IDEONE You can see there from i = 16 , the program is giving wrong output. There should be all 1s in every number. Can anyone please tell me

  • Why this is giving wrong result even in this small range ?
  • And how to avoid this type of calculation problem ?
    Thanks in advance ❤️❤️❤️

Solution

  • The C++ double type is typically stored (in memory) in 64-bit "double-precision floating-point" format.

    While this allows you to represent and calculate on both very large, and very small, numbers (relative to other common c++ datatypes) it only does this with a certain precision.

    This means that you can only rely on 15-17 digits being exact. Anything beyond that is the result of rounding to the nearest value that can be represented in the specific amount of memory (again, typically 64-bits).

    I hope this answers the first question. There's much more to learn about this, for example in this Wikipedia article: https://en.wikipedia.org/wiki/Double-precision_floating-point_format

    As for the second question, the answer is that it depends. It depends on just how big the numbers you want to represent are.

    For example, if you are just working with positive integers, you can extend the range somewhat by switching to unsigned long long int which get's you to 18,446,744,073,709,551,615 (not quite enough for the code at hand, so I'm mostly mentioning it for completeness).

    If that's not sufficient you probably want to be looking for a c++ library for big numbers.

    Google c++ big number library and/or c++ big integer library.