Rakesh Sharma
Rakesh Sharma

Reputation: 25

Calculation using power function gave wrong answers for large numbers

I have two values p=19, q=14. I want to calculate pq using the power function pow(p, q).

Here is my code:

long long p=19,q=14;
cout<<pow(p,q);

The correct answer is: 799006685782884121 but my code gives me 799006685782884096 which is incorrect.

I have also tried doing these calculations using unsigned long long instead of long long, but this didn't help.

Upvotes: 0

Views: 463

Answers (1)

jotik
jotik

Reputation: 17900

The pow function is defined as:

double pow(double x, double y);

Which means that it takes floating point arguments and returns a floating point result. Due to the nature of floating point numbers, some numbers can not be exactly represented. The result you're getting is probably the closest match possible.

Note also that you're doing two (probably lossy) conversions:

  • converting the arguments from long long to double, and
  • converting the result of the function from double to long long.

Upvotes: 3

Related Questions