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.
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; }
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With