0

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

Rd7
  • 45
  • 2
  • 9
  • `n <<= a` is equivalent to `n *= 2^a` or `n = n * 2^a` where `2^a` is the ath power of 2 and `n >>= a` is equivalent to `n /= 2^a` or `n = n / 2^a` where, again, `2^a` is the ath power of 2. – hinafu Apr 09 '13 at 14:26
  • here ´one >>= 2;´ so we need to return ´one´ or ´res´ ? – Rd7 Apr 09 '13 at 14:35

1 Answers1

0

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
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • I guess OP is asking why "one" should start at the highest power of four <= than the argument." – taocp Apr 09 '13 at 14:40