0

As we know that the range of unsigned long long int is 0 to 18,446,744,073,709,551,615

Means , unsigned long long int is capable for handling 19-20 digits easily.

So, I want to know why my this program is returning different value.

Program :

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long int ulli;
int main()
{
    double a,b;
    cin>>a>>b;
    ulli result = (ulli)pow(a,b);
    cout<<"result = "<<result<<"\n";
}

After giving this input : a=15 , b=15

Expected output is : 437893890380859375 ( 18 digits number )

But , it is giving this : result = 437893890380859392 ( last 2 digits are different ).

Can anyone help me out why I am getting different result ?

Onur A.
  • 3,007
  • 3
  • 22
  • 37
SAPJV
  • 115
  • 8
  • 6
    `18 digits number` that is beyond the # of significant digits that double has. – drescherjm Dec 17 '18 at 17:35
  • Could you please elaborate ?? I am not getting you.. – SAPJV Dec 17 '18 at 17:39
  • 5
    https://en.wikipedia.org/wiki/Double-precision_floating-point_format ***The 53-bit significand precision gives from 15 to 17 significant decimal digits precision (2−53 ≈ 1.11 × 10−16)*** – drescherjm Dec 17 '18 at 17:41
  • 2
    I'd like to add what @drescherjm said that the return type of `pow(double, double)` is `double`, and the fact that you cast it to `unsigned long long int` does not change anything regarding the precision you can get – Aykhan Hagverdili Dec 17 '18 at 17:59
  • 1
    probably you are solving some problem on hackerrank, SPOJ or similar site. I'm pretty sure you have to use modular algebra (it is usual problem there). I recommend ask question describing your actual problem (provide a link to site task). – Marek R Dec 17 '18 at 18:01
  • I recommend comparing the `pow` in your case with a loop that performs exponentiation (using integral numbers). Remember, `pow` is floating point. – Thomas Matthews Dec 17 '18 at 18:43
  • Side note: `pow` is designed to handle really nasty smurf like computing e to the power of pi. While some implementations include shortcuts for simple cases like squaring and compilers are getting smarter and smarter at recognizing and replacing common patterns, `pow` is often overkill for exponentiation of integers. In addition, due to floating point imprecision you quite often wind up off by one even with simple and small exponents due to truncation when transforming 24.999999 back to an integer. – user4581301 Dec 17 '18 at 19:13
  • And now for the usual note: Avoid using `using namespace std;` ([why](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)) and do not use `#include` ([why](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)). Together they amplify the other's worst effects, leading to a veritable minefield of identifiers you don't even know exist and now must avoid. – user4581301 Dec 17 '18 at 19:19

0 Answers0