How ceil function works in c++?

270 Views Asked by At

When I execute this code the value of ans1, ans2 is 50002896 and 50005000.
I know there is some issues with ceil function but was not able to figure out the exact cause.

#include <bits/stdc++.h>
using namespace std;
int main()
{
      long long ans1 = 0, ans2 = 0;

      for (long long i = 1; i <= 10000; i++)
      {
            ans1 = ans1 + ceil((float)i / 1);
            ans2 = ans2 + i;
      }
      cout << ans1 << " " << ans2 << endl;
}
2

There are 2 best solutions below

0
wohlstad On BEST ANSWER

The source of the problem is not the ceil function, but rather that not all integers can be represented accuratly as floating point values.

Some more info about floating point representation: Wikipedia IEEE 754. And a related post: Which is the first integer that an IEEE 754 float is incapable of representing exactly?.

The following code is a minimal demonstration of the same issue that causes your issue:

float f1 = 100000000;
f1++;
std::cout << std::to_string(f1) << std::endl;

[Wrong] Output (expected: +1):

100000000.000000

One approach would be to use double instead of float.
This will not solve the principle issue, but will make the range of representable integers a lot bigger:

double f1 = 100000000;
f1++;
std::cout << std::to_string(f1) << std::endl;

Output:

100000001.000000

Some side notes:

  1. better to avoid #include <bits/stdc++.h> - see here: Why should I not #include <bits/stdc++.h>?.
  2. better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
0
Sammed On

First, try to use specific headers like #include , in this case, .because #include <bits/stdc++.h> will bring lots of junk.

So the issue is with float not ceil explained below

floating-point values do not represent exact values.

Code:-

#include <iostream>
#include <iomanip>
using namespace std;

// Driver Code
int main()
{
    float num1 = 10000.29;
    float num2 = 10000.2;

    // Output should be 0.0900000000
    cout << std::setprecision(15)
        << (num1 - num2);
    return 0;
}

Output :-

0.08984375