Change fast inverse square root to regular square root?

How to edit this code to get regualr square root instead of inverse square root?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
float q_qsqrt( float number)
{
    long i;
    float x2,y;
    const float threehalfs = 1.5f;

    x2 = number * 0.5f;
    y = number;
    i = * ( long * ) &y;
    i = 0x5f3759df - ( i >> 1);
    y = * ( float *) &i;
    y = y * ( threehalfs - ( x2 * y * y) );

    return y;
}


I think that magic number 0x5f3759df have to change here, but i'm not smart.
All help is much appreciated and thank you for reading.
Last edited on
google the bablyonian method (its really simple and they did this by hand a very long time ago!). or use sqrt() in <cmath>
also prefer double and never float unless you have a requirement to use float specifically.
Last edited on
Thank you jonnin. I used approximations that depend on the floating point representation section from your link and my function look like this now:

1
2
3
4
5
6
7
8
9
10
11
12
float q_sqrt( float number)
{
    long i;
    float y;
    y = number;

    i = * ( long * ) &y;
    i = (1 << 29) + (i >> 1) - (1 << 22) + (-0x4b0d2);
    y = * ( float *) &i;

    return y;
}
Topic archived. No new replies allowed.