Permissible accuracy with unsigned lengths

So, I'm trying to make pow (x, y). Where x and y are unsigned longs and the result is stored in unsigned long. This result will be less than 2 ^ 63, so I have to do it. But since it returns a floating point number, I get inaccurate results for large numbers. Do I need to get an accurate result without using external libraries like bignum? I know that I can just do x * xa Y times, but I'm trying to avoid this because I'm trying to make my program faster.

+4
source share
3 answers

The pow function returns a double that has problems with precision, and when you finish it to the end, then you will certainly get precision. As far as I know, if you are not using the library, it is impossible to get an accurate result using only the pow function.

You can also look at squaring , as well as look at 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;
}
+5
source

powby definition, is inaccurate. It uses exp(y*log(x))as a way to emulate x ^ y. If you need full accuracy, you need to either use an external library or make your own version pow.

+1
source

I am not sure about your code. But I think your code is like this

unsigned long x,y;
x=...//
y=...//

unsigned long res=pow(x,y);

It is not right. Since pow () always returns a double type.

double pow(double x, double y) 

why did you get a double type of number.

To get the correct number, you can do the following:

    unsigned long x,y;
    x=...//
    y=...//

    unsigned long res=(unsigned long)pow(x,y);
-1
source

Source: https://habr.com/ru/post/1612751/


All Articles