Slashdot Log In
Origin of Quake3's Fast InvSqrt()
Posted by
Zonk
on Fri Dec 01, 2006 02:20 PM
from the i-know-you-were-dying-inside-without-this dept.
from the i-know-you-were-dying-inside-without-this dept.
geo writes "Beyond3D.com's Ryszard Sommefeldt dons his seersucker hunting jacket and meerschaum pipe to take on his secret identity as graphics code sleuth extraordinaire. In today's thrilling installment, the origins of one of the more famous snippets of graphics code in recent years is under the microscope — Quake3's Fast InvSqrt(), which has been known to cause strong geeks to go wobbly in the knees while contemplating its simple beauty and power."
This discussion has been archived.
No new comments can be posted.
Origin of Quake3's Fast InvSqrt()
|
Log In/Create an Account
| Top
| 402 comments
| Search Discussion
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
A famous quote (Score:5, Funny)
(http://www.naawp.org/)
Re:A famous quote (Score:5, Informative)
(Last Journal: Saturday June 30, @01:22AM)
Re:A famous quote (Score:5, Funny)
(http://evilempire.ath.cx/)
Re:A famous quote (Score:5, Informative)
Re:A famous quote (Score:4, Interesting)
(http://wickedindustry.com/)
This is why console games (ps, ps2, xbx, 360, bla bla bla huj) actually stays competitive to PC (more powerful, of course) - since developers has a good idea about actual CPU/GPU available at any given moment, they can safely close to the border way more confidently than on pc. And on PC they usually resort to generic 'will give you the best that I can' routines anyway.
(at least that what I can say after observing xbox360 devel team for 6 months. scary stuff, they do, scary stuff.)
Re:A famous quote (Score:5, Funny)
(http://mogrify.org/)
Interesting smiley... is that a dead man with a fraction in his mouth and a prominent Adam's Apple, wearing a bow tie and a dress and standing on a toy race car?
What's your point, man?
Re:A famous quote (Score:4, Insightful)
(http://wandership.ca/ | Last Journal: Tuesday February 01 2005, @08:03PM)
Really? What if the number is negative?
I think you mean to say "the original number", not "the absolute value of the original number". When given a negative argument, this composition will either return an error (because there is no support for complex numbers) or a negative result equal to the input.
Re:A famous quote (Score:5, Informative)
Slow:
const float length = sqrt( v.x*v.x + v.y*v.y + v.z*v.z );
v.x
v.y
v.z
Fast:
const float recip_length = InvSqrt( v.x*v.x + v.y*v.y + v.z*v.z );
v.x *= recip_length;
v.y *= recip_length;
v.z *= recip_length;
The 2nd version has no divides, and no call to sqrt, which makes it *loads* faster.
Re:A famous quote (Score:4, Informative)
(http://en.wikipedia.org/wiki/User:Raul654)
Re:A famous quote (Score:4, Informative)
(http://www.piratetoystore.com/)
Re: A better question: (Score:5, Informative)
It starts by taking a guess at the right answer, and then improving the guess until it's accurate enough to use.
The first step depends heavily on the fact that a floating point number on a computer is represented as a significand (aka mantissa) and an exponent (a power of two). For the moment, consider taking just the square root of X instead of its inverse. You could separate out the exponent part of the floating point number, divide it by two, and then put the result back together with the original significand, and have a reasonable starting point.
From there, you could improve your guesses to get a better approximation. The simplest version of that would be like a high-low game -- you split the difference between the current guess and the previous guess, and then add or subtract that depending on whether your previous guess was high or low. Eventually, you'll get arbitrarily close to the correct answer.
This can take quite a few iterations to get to the right answer though. To improve that, Newton-Raphson looks at the curve of the function you're working with, and projects a line tangent to the curve at the point of the current guess. Where that line crosses the origin gives you the next guess. That's probably a lot easier to understand from picture [sosmath.com].
In this case, we're looking for the inverse square root, which changes the curve, but not the basic idea. As a general rule, the closer your first guess, the fewer iterations you need to get some particular level of accuracy. That's the point of the:
While the originator of this constant is unknown, and some of it is rather obscure, the basic idea of most of it is fairly simple: we start by shifting the original number right a bit. This divides both the mantissa and the exponent part by two, with the possibility that IF the exponent was odd, it shifts a bit from the exponent into the mantissa. The subtraction from the magic number then does a couple of things. For one thing, if a bit from the exponent was shifted into the mantissa, it removes it. The rest of the subtraction is trickier. If memory serves, it's based on the harmonic mean of the difference between sqrt(x) and (x/2) for every possible floating point number of the size you're using.
This is where the fact that it's 1/sqrt(x) instead of sqrt(x) means a lot: 1/sqrt(x) is a curve, but it's a fairly flat curve -- much flatter than sqrt(x). The result is that we can approximate a point on the curve fairly accurately with a line. In this case, it's really two lines, which gets it a bit closer still.
From there, the number has had a bit of extra tweaking done -- it doesn't actually give the most accurate first guess, but its errors are often enough in the opposite direction from those you get in the Newton-Raphson iteration steps that it gives slightly more accurate final results.
Correction (Score:5, Informative)
(Last Journal: Tuesday September 19 2006, @01:23PM)
I believe you meant to say x^(-1/2)
Too bad the people modding you up don't have math degrees. =P
Re:Correction (Score:4, Insightful)
(http://slashdot.org/)
Re:A famous quote (Score:5, Informative)
(Last Journal: Friday June 11 2004, @11:15AM)
This is great for a 3D rendering application, but in a game speed is critical. This pair of calculations involves a square root and a divide. Both of thse are at least an order of magnitude slower than multiplications and additions.
So what this function does is provide a value you can multiply each component by to get a unit vector.
Well, there's the what and why parts. As for the , I have no idea. I think it uses magic.
Re:A famous quote (Score:5, Insightful)
(http://people.xiph.org/~jm/)
You mean that Newton thought about taking advantage of the IEEE float format to initialize the algorithm using "i = 0x5f3759df - (i>>1);"? Wow, now that's a clever guy!
Re:A famous quote (Score:4, Funny)
(http://slashdot.org/)
int i = *(int*)&x;
i = 0x5f3759df - (i >> 1);
Then I'm afraid the whole article is going to be lost on you...
We've got a floating point being operated on as an integer.
We've got a mysterious constant.
We've got a two's complement sign-flip combined with a bit-shift.
The only thing missing from this party is hookers and beer.
Re:A famous quote (Score:5, Informative)
(Last Journal: Friday November 10 2006, @02:16PM)
Carmack quite graciously denied the code was his and helped direct the author closer to the true source.
And so why do we care? (Score:2, Insightful)
[Insert rant about software patents]
Re:And so why do we care? (Score:5, Funny)
(http://offthegrid.1337hax0r.com/ | Last Journal: Wednesday October 18 2006, @12:56PM)
I was a little worried when Slashdot posted the Britney Spears beaver pictures, but they now have their credibility back as the home of "News for Nerds".
Re:And so why do we care? (Score:5, Funny)
Re:And so why do we care? (Score:5, Funny)
Re:And so why do we care? (Score:5, Funny)
(http://www.timewarp.org/ | Last Journal: Monday September 30 2002, @08:49AM)
--
Evan
Re:And so why do we care? (Score:5, Informative)
(Last Journal: Sunday April 22 2007, @01:32PM)
Re:And so why do we care? (Score:5, Interesting)
(Last Journal: Thursday July 12, @12:30PM)
Mods: I want +5, Funny for this. No, no, wait: +5, Informative. No, wait, anyone can google something and be "informative." I want a +5, Interesting.
Thanks.
I know who wrote it (Score:5, Funny)
(http://circletimessquare.com/)
Obviously SCO's intellectual property! (Score:5, Funny)
This paper seems to have the info (Score:5, Informative)
(http://geocities.com/nelstomlinson/index.html)
Re:This paper seems to have the info (Score:5, Funny)
(http://home.mchsi.com/~toasty/)
What's with use of Pointers? (Score:3, Interesting)
(http://millionnumbers.com/)
Can someone enlighten me?
Re:What's with use of Pointers? (Score:5, Informative)
*(int*) &x treats the bits as an integer, with no behind the scenes conversion to an actual int value.
Re:What's with use of Pointers? (Score:5, Informative)
(http://www.music.mcgill.ca/~sinclair)
If you do this:
int i = (int)3.0f;
You get i=3, like what you'd get from the floor() function.
If you do this:
float f = 3.0f;
int i = *(int*)
Then i contains a bit-for-bit copy of the IEEE floating-point representation of 3.0.
It's because C knows how to cast a float to an int by applying the floor function. However, if you do it the second way, you aren't casting a float to an int, you are casting a pointer-to-float to a pointer-to-int and then dereferencing it.
By the way, I just wanted to say... this is one of the most interesting things I've read on Slashdot in a while. Wow. That function is just amazing. I only wish I understood how it worked. I know nothing about what a "Newton-Raphson iteration" is.
Re:What's with use of Pointers? (Score:5, Informative)
(http://www.dsbscience.com/)
You start with some INITIAL GUESS (the real beauty of this algorithm) X(0), then apply:
X(n+1) = X(n) - f(X(n)) / f'(X(n))
where
X(n+1) is the NEXT guess after the value you 'know',
X(n) is that most recent value you know,
f(X(n)) is the function evaluated at X(n) and
f'(X(n)) is the first derivative of f(x) evaluated at X(n).
It's not foolproof and a BOTH whether it converges at al AND how FAST it converges depends on the initial guess, X(0)
The "Secant Method" is an improvement that makes it a little 'smarter,' at the expense of more computation (this is often a positive trade-off on numerical modeling codes, since the 'smarter' algorithm does tend to converge faster). There are other improvements as well, such as the Los Alamos Linear Feedback Solver (a slightly modified secant method that converges about 10-17% faster, at least for some types of problems) that I use in my own codes.
Obligatory wikipediea followup: Newton's Method [wikipedia.org]
Re:What's with use of Pointers? (Score:5, Informative)
The trick of this function is to take the 32 bits of data that are really a float, but process it as if it's an integer. So you take that cumbersome number 21 as a float, then BAM! presto, turn it directly to an integer not through type conversion, but by simply treating those same 32 bits as if they were representing an integer all along.
Let's use the number 21 as an example in the function call.
The binary representation of 21 as a float is 01000001 10101000 00000000 00000000 (broken into 8-bit words for clarity). The function then goes to create a new integer i, whose value is also 01000001 10101000 00000000 00000000 (which happens to be 1101529088 in decimal). The magical line of the code, i = 0x5f3759df - (i>>1), takes that integer i, shifts its bits one to the right (turning our 01000001 10101000 00000000 00000000 into 00100000 11010100 00000000 00000000, or 550764544 in decimal), then subtracts it (still doing integer math here) from 0x5f3759df (which is 01011111 00110111 01011001 11011111 or 1597463007 in decimal), and winds up with 00111110 01100011 01011001 11011111 (or 1046698463 in decimal).
Now, for its next trick, it takes that wonky integer 1046698463, and turns it back into a floating point number, by the same trick used above, i.e. simply by looking at those same 32 bits, and pretending they're a float, not an int. The binary representation of 1046698463, 00111110 01100011 01011001 11011111, is the same as 0.22202251851558685 in float.
From here on out, it's all floating math. Apply the Newton-Rhapson method (thats the next line), we get x = 0.22202251851558685 * (1.5 - ( (21*.5) * 0.22202251851558685^2 )) = 0.218117811. We return this value at the closing of the function. As it turns out, the inverse square root of 21 is 0.21821789... (thanks Google calc). So, I have no idea WHY the Float to Int to Float trick works, but it works very well.
Whew!
Re:What's with use of Pointers? (Score:5, Informative)
I'll take a swing at this one. It's because the author doesn't want the value of x, but the integer representation of the value at x's memory address.
If x is 3.14159, (2) will result in i==3, whereas (1) will result in whatever the 4-byte IEEE-754 representation of 3.14159 is (0x40490FD0, if Google is correct). By using (1), the author is able to use integer bitwise opeartions (>>) to perform "free" floating point operations. When i is sent back into floating point form via:
x = *(float*)
x now contains the value of the integer operation:
i = 0x5f3759df - (i >> 1);
which was presumably faster than an identical floating point operation. It's a nifty little solution, especially with regard to the selection of the magic number.
Re:What's with use of Pointers? (Score:5, Informative)
(http://ewhac.best.vwh.net/ | Last Journal: Saturday August 18 2001, @10:28PM)
int i = (int)x;
Then C will simply convert the float value into an integer value (throwing away fractional part). But this isn't what we want. We want to operate on the bits of an IEEE floating point value directly, and integers are the best way to do that.
So first, we lie to the compiler by telling it we have a pointer to an int:
(int *) &f
And then we deference the pointer to get it into an operable int:
i = *(int *) &f
Note what's important here is to keep the compiler from modifying any part of the original 32-bit value.
Schwab
Old and busted: Duff's device (Score:4, Funny)
(http://slashdot.org/~Stavr0/journal/ | Last Journal: Thursday January 19 2006, @01:18PM)
Naah, just kidding. They both deserve a spot in the Clever Hacks Hall of Fame
Hmm... (Score:2, Funny)
(http://spiderweblabs.com/)
Poor function name (Score:4, Insightful)
(http://paul-mclaughlin.com/)
Re:Poor function name (Score:4, Funny)
It was fast (Score:4, Informative)
(http://www.icarusindie.com/)
That page compares the time it takes to calculate the sqrt various ways including Carmacks. Short version is that modern processors are significantly faster since it can be done in hardware. It may still be useful in cases where the processor doesn't have the sqrt function available.
His version took 428 cycles compared to 107 cycles doing it in hardware on the same system.
Re:It was fast (Score:5, Insightful)
Re:It was fast (Score:5, Informative)
rsqrtss xmm1, xmm0
about 5 cycles. And it can pipeline.
Not a fan of x86? Maybe altivec...
vrsqrtefp V2, V1
depends, but 12 cycles probably and pipelined.
On PS3's SPU it's rsqrte (6 cycles), on 3dNow it's pfrsqrt (8 cycles) both pipelined. Even PS2 had rsqrt (13 cycles). There's just no reason for software reciprocal square root. It's a cool trick, but it's not even useful anymore.