Question

i am trying to find the square root of a fixed point and i used the following Calculation to find an approximation of the square root using an integer algorithm. The algorithm is described in Wikipedia: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots

uint32_t SquareRoot(uint32_t a_nInput)
{
    uint32_t op  = a_nInput;
    uint32_t res = 0;
    uint32_t one = 1uL << 30; // The second-to-top bit is set: use 1u << 14 for uint16_t type; use 1uL<<30 for uint32_t type


    // "one" starts at the highest power of four <= than the argument.
    while (one > op)
    {
        one >>= 2;
    }

    while (one != 0)
    {
        if (op >= res + one)
        {
            op = op - (res + one);
            res = res +  2 * one;
        }
        res >>= 1;
        one >>= 2;
    }
    return res;
}

but i am unable to follow whats happening in the code what does the comment // "one" starts at the highest power of four <= than the argument. exactly means. Can someone please hint me whats happening in the code to calculate the square root of the argument a_nInput

Thanks much

Était-ce utile?

La solution

Note how one is initialized.

uint32_t one = 1uL << 30;

That's 230, or 1073741824. Which is also 415.

This line:

    one >>= 2;

Is equivalent to

    one = one / 4;

So the pseudocode for what's happening is:

  • one = 415

  • if one is more than a_nInput

    • one = 414
  • if one is still more than a_nInput

    • one = 413
  • (and so on...)

Eventually, one will not be more than a_nInput.

// "one" starts at the highest power of four less than or equal to a_nInput
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top