Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pow precision with unsigned longs

Tags:

c

precision

pow

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.

like image 651
LifeisHard Avatar asked Oct 22 '15 12:10

LifeisHard


2 Answers

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;
}
like image 59
Rahul Tripathi Avatar answered Oct 03 '22 07:10

Rahul Tripathi


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.

like image 32
Magisch Avatar answered Oct 03 '22 08:10

Magisch