Reputation: 125
So I am trying to do the pow (x, y). Where x and y are unsigned longs and the result is stored in an unsigned long. This result will be smaller than 2^63 so I should be able to do it. But since it returns a floating point number I get inaccurate results for big numbers. Is there anyway to get an exact result without using external libraries like bignum? I know I could simply do x*x a Y times, but that is what I am trying to avoid because I am trying to make my program faster.
Upvotes: 5
Views: 569
Reputation: 7352
pow
is by definition inaccurate. It uses exp(y*log(x))
as a way to emulate x ^ y
. If you want complete precision you either need to use an external library or make your own version of pow
.
Upvotes: 2
Reputation: 147
I am not sure your code. But i guess your code like this
unsigned long x,y;
x=...//
y=...//
unsigned long res=pow(x,y);
This is not right. Because pow() always return double type.
double pow(double x, double y)
that's why you got double type number.
To get right number you can do like this:
unsigned long x,y;
x=...//
y=...//
unsigned long res=(unsigned long)pow(x,y);
Upvotes: -1
Reputation: 172378
pow function returns a double which has precision issues and when you will cast it to long then you are most certain to get the precision issue. As far as I know if you dont use a library then it is not possible to get the accurate result using the pow function alone.
You can also look at Exponentiation by squaring and also look at the barak manos answer where you can try to implement your own pow function as
unsigned long long pow(unsigned long long x,unsigned int y) { unsigned long long res = 1; while (y > 0) { if (y & 1) res *= x; y >>= 1; x *= x; } return res; }
Upvotes: 6