<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Computer Science &#8211; BetterExplained</title>
	<atom:link href="https://betterexplained.com/articles/series/computer-science/feed/" rel="self" type="application/rss+xml" />
	<link>https://betterexplained.com</link>
	<description>Math lessons that click</description>
	<lastBuildDate>Thu, 17 Sep 2026 23:28:22 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>A Simple Introduction To Computer Networking</title>
		<link>https://betterexplained.com/articles/a-simple-introduction-to-computer-networking/</link>
					<comments>https://betterexplained.com/articles/a-simple-introduction-to-computer-networking/#disqus_thread</comments>
		
		<dc:creator><![CDATA[kalid]]></dc:creator>
		<pubDate>Mon, 16 Mar 2009 09:00:30 +0000</pubDate>
				<category><![CDATA[Guides]]></category>
				<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://betterexplained.com/articles/a-simple-introduction-to-computer-networking/</guid>

					<description><![CDATA[Most networking discussions are a jumble of acronyms. Forget the configuration details — what are the insights? Networking is about communication Text is the simplest way to communicate Protocols are standards for reading and writing text Beneath the details, networking is an IM conversation. Here’s what I wish someone told me when learning how computers [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Most networking discussions are a jumble of acronyms. Forget the configuration details — what are the insights?</p>

<ul>
<li><strong>Networking is about communication</strong></li>
<li><strong>Text is the simplest way to communicate</strong></li>
<li><strong>Protocols are standards for reading and writing text</strong></li>
</ul>

<p>Beneath the details, networking is an IM conversation. Here’s what I wish someone told me when learning how computers communicate.</p>

<h2>TCP: The Text Layer</h2>

<p>The Transmission Control Protocol (TCP) provides the handy illusion that we can “just” send text between two computers. TCP relies on <a href="https://en.wikipedia.org/wiki/Internet_Protocol">lower levels</a> and can send binary data, but ignore that for now:</p>

<ul>
<li><strong>TCP lets us Instant Message between computers</strong></li>
</ul>

<p>We IM with Telnet, the ‘notepad’ of networking: telnet sends and receives plain text using TCP. It’s a chat client peacefully free of ads and unsolicited buddy requests.</p>

<p>Let’s talk to Google using <a href="http://support.microsoft.com/kb/279466">telnet</a> (or <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/">putty</a>, a better utility):</p>

<pre><code>telnet google.com 80
[connecting...]
Hello Mr. Google!
</code></pre>

<p>We connect to google.com on port 80 (the default for web requests) and send the message “Hello Mr. Google!”. We press Enter a few times and await the reply:</p>

<pre><code>&lt;html&gt;
...
&lt;h1&gt;Bad Request&lt;/h1&gt;
Your client has issued a malformed or illegal request
...
&lt;/html&gt;
</code></pre>

<p>Malformed? Illegal? <em>The mighty Google is not pleased</em>. It didn’t understand us and sent HTML telling the same.</p>

<p>But, we had a conversation: text went in, and text came back. In other words: </p>

<p><img decoding="async" src="https://betterexplained.com/wp-content/uploads/networking/tcp_chat.png" alt="A Simple Introduction To Computer Networking" /> </p>

<h2>Protocols: The Forms To Fill Out</h2>

<p>Unstructured chats are too carefree — how does the server know what we want to do? We need a <em>protocol</em> (standard way of communicating) if we’re going to make sense.</p>

<p>We use protocols all the time</p>

<ul>
<li>Putting “to” and “from” addresses in special places on an envelope</li>
<li>Filling out bank forms (special place for account number, deposit amount, etc.)</li>
<li>Saying “Roger” or “10-4” to indicate a radio request was understood</li>
</ul>

<p>Protocols make communication clear.</p>

<h2>Case Study: The HTTP Protocol</h2>

<p>We see HTTP in every url: <a href="https://google.com/">http://google.com/</a>. What does it mean?</p>

<ul>
<li>Connect to server google.com (Using TCP, port 80 by default)</li>
<li>Ask for the resource “/” (the default resource)</li>
<li>Format the request using the Hypertext Transfer Protocol</li>
</ul>

<p>HTTP is the “form to fill out” when asking for the resource. Using the HTTP format, the above request looks like this:</p>

<pre><code>GET / HTTP/1.0
</code></pre>

<p>Remember, <em>it’s just text</em>! We’re asking for a file, through an IM session, using the format: [Command] [Resource] [Protocol Name/Version].</p>

<p>This command is “IM’d” to the server (your browser adds extra info, a detail for another time). Google’s server returns this response:</p>

<pre><code>HTTP/1.0 200 OK
Cache-Control: private, max-age=0
Date: Sun, 15 Mar 2009 03:13:39 GMT
Expires: -1
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=5cc6…
Server: gws
Connection: Close

&lt;html&gt;
(Google web page, search box, and cute logo)
&lt;/html&gt;
</code></pre>

<p>Yowza. The bottom part is HTML for the browser to display. But why the junk up top?</p>

<p>Well, suppose we just got the raw HTML to display. But what about errors: if the server crashed, the file wasn’t there, or google just didn’t like us?</p>

<p>Some <em>metadata</em> (data about data) is useful. When we order a book from Amazon <strong>we expect a packing slip</strong> describing the order: the intended recipient, price, return information, etc. You don’t want a naked book just thrown on your doorstep.</p>

<p>Protocols are similar: the recipient wants to know if everything was OK. Here we see infamous status codes like 404 (resource not found) or 200 (everything OK). These headers aren’t the real data — they’re the packing slip from the server.</p>

<h2>Insights From Protocols</h2>

<p>Studying existing, popular systems is a great way to understand engineering decisions. Here are a few:</p>

<p><strong>Binary vs Plain Text</strong></p>

<p><a href="https://betterexplained.com/articles/a-little-diddy-about-binary-file-formats/">Binary data</a> is more efficient than text, but more difficult to debug and generate (how many hex editors do you know to use?). Lower-level protocols, the backbone of the internet, use binary data to maintain performance. Application-level protocols (HTTP and above) use text data for ease of interoperability. You don’t have religious wars about endian issues with HTTP.</p>

<p><strong>Stateful vs. Stateless</strong></p>

<p>Some protocols are stateful, which means the server remembers the chat with the client. With SMTP, for example, the client opens a connection and issues commands one at a time (such as adding recipients to an email), and closes the connection. Stateful communication is useful in transactions that have many steps or conditions.</p>

<p>Stateless communication is simpler: you send the entire transaction as one request. Each “instant message” stands on its own and doesn’t need the others. HTTP is stateless: you can request a webpage without introducing yourself to the server.</p>

<p><strong>Extensibility</strong></p>

<p>We can’t think of everything beforehand. How do we extend old protocols for new users?</p>

<p>HTTP has a simple and effective “header” structure: a metadata preamble that looks like “Header:Value”.</p>

<p>If you don’t recognize the header sent (new client, old server) just ignore it. If you were expecting a header but don’t see it (old client, new server), just use a default. It’s like having an “Anything else to tell us?” section in a survey.</p>

<p><strong>Error Correction &amp; Reliability</strong></p>

<p>It’s the job of lower-level protocols like TCP to make sure data is transmitted reliably. But higher-level protocols (like HTTP) need to make sure it’s the <em>right</em> data. How are errors handled and communicated? Can the client just retry or does the server need to reset state?</p>

<p>HTTP comes with its own set of error codes to handle a variety of situations.</p>

<p><strong>Availability</strong></p>

<p>The neat thing about networking is that works on one computer. Memcached is a great service to cache data. And guess what? It uses plain-old text commands (over TCP) to save and retrieve data.</p>

<p>You don’t need complex COM objects or DLLs – you start a Memcached server, send text in, and get text out. It’s language-neutral and easy to access because any decent OS supports networking. You can even telnet into Memcached to debug it.</p>

<p>Wireless routers are similar: they have a control panel available through HTTP. There’s no “router configuration program” — you just connect to it with your browser. The router serves up webpages, and when you submit data it makes the necessary configuration changes.</p>

<p>Protocols like HTTP are so popular you can <em>assume</em> the user has a client.</p>

<p><strong>Layering Protocols</strong></p>

<p>Protocols can be layered. We might write a resume, which is part of a larger application, which is stuffed into an envelope. Each segment has its own format, blissfully unaware of the others. Your envelope doesn’t care about the resume — it just wants the to: and from: addresses written correctly.</p>

<p>Many protocols rely on HTTP because it’s so widely used (rather than starting from scratch, like Memcached, which needs efficiency). HTTP has well-understood methods to define resources (URLs) and commands (GET and POST), so why not use them?</p>

<p>Web services do just that. The SOAP protocol crams XML inside of HTTP commands. The REST protocol embraces HTTP and uses the existing verbs as much as possible.</p>

<h2>Remember: It’s All Made Up</h2>

<p>Networking involves <em>human conventions</em>. Because plain text is ubiquitous and easy to use, it is the basis for most protocols. And TCP is the simplest, most-supported way to exchange text.</p>

<p><strong>Remembering that everything is a plain text IM conversation</strong> helps me wrap my head around the inevitable networking issues. And sometimes you need to jump into HTTP to understand <a href="https://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/">compression</a> and <a href="https://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/">caching</a>.</p>

<p>Don’t just memorize the details; see protocols as strategies to solve communication problems. Happy networking.</p>

]]></content:encoded>
					
					<wfw:commentRss>https://betterexplained.com/articles/a-simple-introduction-to-computer-networking/feed/</wfw:commentRss>
			<slash:comments>21</slash:comments>
		

			</item>
	<item>
		<title>The Quick Guide to GUIDs</title>
		<link>https://betterexplained.com/articles/the-quick-guide-to-guids/</link>
					<comments>https://betterexplained.com/articles/the-quick-guide-to-guids/#disqus_thread</comments>
		
		<dc:creator><![CDATA[kalid]]></dc:creator>
		<pubDate>Wed, 18 Apr 2007 23:03:48 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://betterexplained.com/articles/the-quick-guide-to-guids/</guid>

					<description><![CDATA[Our world is numbered. Books have ISBNs and products have barcodes. Cars have VINs , even people have social security numbers. Numbers help us reference items unambiguously. “John Smith” may be many people, but Social Security Number 123-45-6789 refers to one person exactly. A GUID (globally unique identifier) is a bigger, badder version of this [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Our world is numbered. Books have ISBNs and products have barcodes. Cars have <a href="https://en.wikipedia.org/wiki/Vehicle_identification_number">VINs</a>, even people have social security numbers.</p>

<p>Numbers help us reference items unambiguously. “John Smith” may be many people, but Social Security Number 123-45-6789 refers to one person exactly.</p>

<p>A GUID (globally unique identifier) is a bigger, badder version of this type of ID number. You may see the term UUID tossed about (universally unique identifier), a nitpicky word for those whose numbers are unique not only within the globe, but throughout the entire universe.</p>

<p>Any way you title it, GUIDs or UUIDs are just big, gigantic ID numbers.</p>

<h2>The Problem With Counting</h2>

<p>“We don’t need no stinkin’ GUIDs,” you may be thinking between gulps of Top Ramen, “I’ll just use regular numbers and start counting up from 1.”</p>

<p>Sure, it sounds easy. Just start with ISBN #1 and add one for each new book. But problems arise:</p>

<ul>
<li>Who does the counting? A central authority?</li>
<li>Who handles simultaneous requests and eliminates duplicates?</li>
<li>Can IDs be shared between products? Is Social Security Number 1 different from ISBN 1?</li>
<li>Can people guess what the next ID will be? How many IDs have been issued?</li>
</ul>

<p>The problem with counting is that we want to <strong>create ID numbers without the management headache</strong>.</p>

<h2>GUIDs to the Rescue</h2>

<p>GUIDs are large, enormous numbers that are nearly guaranteed to be unique. They are usually 128 bits long and look like this <a href="https://betterexplained.com/articles/numbers-and-bases/">in hexadecimal</a>:</p>

<p><code>30dd879c-ee2f-11db-8314-0800200c9a66</code></p>

<p>The format is a well-defined sequence of 32 hex digits grouped into chunks of 8-4-4-4-12. This gives us <code>2^128</code> or about <a href="http://instacalc.com/51569">10^38 numbers</a>.</p>

<iframe src="https://instacalc.com/51569/embed" width="600" height="250" frameborder="0"></iframe>

<p>Here’s the thinking behind GUIDs:</p>

<ul>
<li><p>If you pick a huge random number (39 digits long), it’s <strong>really unlikely</strong> that someone will pick the same one.</p></li>
<li><p>GUIDs are not tied to a product. A GUID can be used for people, cars, files, webpages, colors, anything. With regular registration numbers, you start counting at 1 and numbers can overlap. Social Security Number 123-45-6789 is different from ISBN 123456789 which is different from barcode 123456789. This isn’t an issue with GUIDs.</p></li>
<li><p>It’s up to the person reading the GUID to figure out the context of the GUID. There are so many GUIDs that you can use them to number everything and not run out.</p></li>
</ul>

<p><strong>GUIDs give you a unique serial number that can be used on any item in the universe.</strong></p>

<h2>The Great GUID Shortage</h2>

<p>When learning about GUIDs, it feels like 39 measly digits aren’t enough. Won’t we run out if people get GUID-crazy, assigning them for everything from their pets to their favorite bubble gum flavor?</p>

<p>Let’s see. Think about how big the Internet is: Google has billions of web pages in its index. Let’s call it a trillion (10^12) for kicks. Think about every wikipedia article, every news item on CNN, every product in Amazon, every blog post from any author. We can assign a GUID for each of these documents.</p>

<p>Now let’s say everyone on Earth gets their own copy of the internet, to keep track of their stuff. Even crazier, let’s say each person gets their own copy of the internet every second. How long can we go on?</p>

<p><a href="http://instacalc.com/51567">Over a billion years</a>.</p>

<iframe src="https://instacalc.com/51567/embed" width="550" height="250" frameborder="0"></iframe>

<p>Let me say that again. Each person gets a <strong>personal copy of the internet, every second, for a billion years</strong>.</p>

<p>It’s a mind-boggling amount of items, and it’s hard to get our heads around it. Trust me, we won’t run out of GUIDs anytime soon. And if we do? We’ll start using GUIDs with more digits.</p>

<h2>Using GUIDs</h2>

<p>If you want to create GUIDs, try the</p>

<ul>
<li><a href="http://www.famkruithof.net/uuid/uuidgen">Online GUID Generator</a></li>
<li>GUID libraries for <a href="http://us.php.net/uniqid">PHP</a>, <a href="http://search.cpan.org/~rjbs/Data-UUID-1.148/UUID.pm">Perl</a>, <a href="http://raa.ruby-lang.org/project/uuid/">Ruby</a>, <a href="https://docs.python.org/3/library/uuid.html">Python</a>, <a href="http://msdn2.microsoft.com/en-us/library/system.guid.aspx">.NET</a></li>
<li><a href="http://tools.assembla.com/breakout/wiki/FreeSoftware">usesguid plugin</a> for Ruby on Rails: Use a GUID instead of an integer as a primary key in your database.</li>
</ul>

<p>There are several ways to create GUIDs (<a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a> describes the conventions), but you want to avoid that mess and use a library. The general types of GUIDs are:</p>

<ul>
<li><strong>Random:</strong> Just use the system’s random-number generator to create a 128-bit number.</li>
<li><strong>Time-based:</strong> Create a GUID based on the current time.</li>
<li><strong>Hardware-based:</strong> Make a GUID with certain portions based on hardware features, such as the MAC address of a network card. This isn’t great because the GUID isn’t “anonymous” and can be partially traced to the machine that created it.</li>
<li><strong>Content-based (MD5 or SHA-1 hash of data):</strong> Create a GUID based on a hash of the file contents. Files with the same contents will get the same GUID. You can also seed the hash with a unique namespace (like your URL).</li>
</ul>

<p>You can mix-and-match techniques above. If you want duplicate files to have the same GUID, then use GUIDs based on the contents. If you want GUIDs to be unique, even if the contents are the same, then create them randomly or with a combination of file contents and a random number.</p>

<h2>GUID Examples</h2>

<p>Here’s a few things you can do with GUIDs:</p>

<ul>
<li>Unique primary key in databases. This lets database items created on separate machines be merged later without conflict, and without the need for a central server to manage IDs.</li>
<li>Unique filename for uploaded files. If each version of the file gets its own GUID, you can set a <a href="https://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/">long cache expiration time</a>.</li>
<li>Unique name for resources (del.icio.us URL for instacalc: <a href="http://del.icio.us/url/6c5ff0ed608e75724df94a52b05dd6a8">http://del.icio.us/url/6c5ff0ed608e75724df94a52b05dd6a8</a>)</li>
<li>Allow vendors to create and register unique IDs without contacting a central authority (like <a href="https://en.wikipedia.org/wiki/Component_Object_Model">class IDs in COM</a>)</li>
</ul>

<h2>The Tradeoffs with GUIDs</h2>

<p>Like most things in life, GUIDs have benefits and drawbacks. Weigh the features to see if they make sense:</p>

<p>Pros:</p>

<ul>
<li><strong>No central authority:</strong> You avoid the need for management, but can’t keep track of what’s been assigned. A compromise is to generate GUIDs internally and then hand them out.</li>
<li><strong>Easily combined:</strong> You can merge sets of GUIDs from different data sources with a microscopic chance of conflict.</li>
</ul>

<p>Cons:</p>

<ul>
<li><strong>Appear random:</strong> Users cannot easily guess the ID for an object they don’t know. This is good for security, difficult for debugging.</li>
<li><strong>GUID overhead:</strong> GUIDs are an example of the time-space tradeoff. You save time in merging but have to use space to store the large (16-byte) GUID. It may not make sense to have a 16-byte GUID keeping track of a 4-byte item in your database.</li>
</ul>

<h2>GUIDs are not a GUARantee</h2>

<p>There’s one giant caveat for GUIDs: collisions are still possible.</p>

<p>First, the <a href="https://betterexplained.com/articles/understanding-the-birthday-paradox/">birthday paradox</a> shows us the chance of a collision as <a href="https://en.wikipedia.org/wiki/Uuid#Random_UUID_probability_of_duplicates">GUIDs are used</a>.  It’s very, very unlikely that GUIDs will collide, but as more are assigned, there are fewer left to choose from.</p>

<p>Second, a malicious user could try hijacking GUIDs that he knows will be used (assuming the user can assign their own GUIDs), or resubmitting different content to a previous GUID (submitting file A under the hash of file B).</p>

<p>If you are writing software, program defensively and detect cases where the GUID already exists. Give the user an error or even better, recover, create a new GUID on the server side and try again. GUIDs are great, but they aren’t a magic bullet.</p>

<p>As always, we’re never done learning. Read more about GUIDs here:</p>

<ul>
<li><a href="http://www.ietf.org/rfc/rfc4122.txt" title="RFC 4122">A Universally Unique IDentifier (UUID) URN Namespace</a></li>
<li>Coding Horror: <a href="http://www.codinghorror.com/blog/archives/000817.html">Primary Keys vs. GUIDs</a></li>
<li>Wikipedia on <a href="https://en.wikipedia.org/wiki/Guid">GUIDs</a> and <a href="https://en.wikipedia.org/wiki/Uuid">UUIDs</a></li>
</ul>

]]></content:encoded>
					
					<wfw:commentRss>https://betterexplained.com/articles/the-quick-guide-to-guids/feed/</wfw:commentRss>
			<slash:comments>40</slash:comments>
		

			</item>
	<item>
		<title>Understanding Quake&#8217;s Fast Inverse Square Root</title>
		<link>https://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/</link>
					<comments>https://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/#disqus_thread</comments>
		
		<dc:creator><![CDATA[kalid]]></dc:creator>
		<pubDate>Tue, 06 Feb 2007 00:50:09 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/</guid>

					<description><![CDATA[An article and research paper describe a fast, seemingly magical way to compute the inverse square root ( ), used in the game Quake. I'm no graphics expert, but appreciate why square roots are useful. The Pythagorean theorem computes distance between points, and dividing by distance helps normalize vectors. (Normalizing is often just a fancy [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>An <a href="http://www.beyond3d.com/content/articles/8/">article</a> and <a href="http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf">research paper</a> describe a fast, seemingly magical way to compute the inverse square root (<img src="https://betterexplained.com/latex/2bf4b1608fd53d024997.png" alt="$1/\sqrt{x}$" width="44" height="20" style="vertical-align:-4.53px" class="bex-math"></img>), used in the game Quake.</p>

<p>I'm no graphics expert, but appreciate why square roots are useful. The <a href="https://betterexplained.com/articles/measure-any-distance-with-the-pythagorean-theorem/">Pythagorean theorem</a> computes distance between points, and dividing by distance helps normalize vectors. (Normalizing is often just a fancy term for division.)</p>

<p>3D games like Quake divide by distance zillions (yes zillions) of times each second, so "minor" performance improvements help immensely. We don't want to take the square root and divide the regular way: exponentiation and division are really, really expensive for the <span class="caps">CPU.</span></p>

<p>Given these conditions, here's the magic formula to get <img src="https://betterexplained.com/latex/2bf4b1608fd53d024997.png" alt="$1/\sqrt{x}$" width="44" height="20" style="vertical-align:-4.53px" class="bex-math"></img>, as found in Quake (my comments inserted):</p>

<pre><code>
    float InvSqrt(float x){
        float xhalf = 0.5f * x;
        int i = *(int*)&x;            // store floating-point bits in integer
        i = 0x5f3759df - (i >> 1);    // initial guess for Newton's method
        x = *(float*)&i;              // convert new bits into float
        x = x*(1.5f - xhalf*x*x);     // One round of Newton's method
        return x;
    }
</code></pre>

<p>Yowza! Somehow, this code gets <img src="https://betterexplained.com/latex/2bf4b1608fd53d024997.png" alt="$1/\sqrt{x}$" width="44" height="20" style="vertical-align:-4.53px" class="bex-math"></img> using only <strong>multiplication</strong> and <strong>bit-shift operations</strong>. There's no division or exponents involved -- how does it work?</p>

<p><strong>My Understanding:</strong> This incredible hack <em>estimates</em> the inverse root using Newton's method of approximation, and starts with a great initial guess.</p>

<p>To make the guess, it takes floating-point number in scientific notation, and negates &amp; halves the exponent to get something close to the inverse square root. It then runs a round of Newton's approximation method to further refine the estimate and tada, we've got something near the inverse square root.</p>

<h2>Newton's Method of Approximation</h2>

<p>Newton's method can be used to find approximate roots of any function. You can keep iterating the method to get closer and closer to the root, but this function only uses 1 step! Here's a crash-course on Newton's method (it was new to me):</p>

<p>Let's say you have a function f(x) and you want to find its root (aka where f(x) = 0). Let's call your original guess "g". Newton's method gives you a way to get a new, better guess for the root:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/f89a247489cad43a322457f9281a0f37.png' width='175' height='44' alt='\displaystyle{\text{new guess} = g - \frac{f(g)}{f&#039;(g)}}' class='tex'></p>

<p>You can keep repeating this process (plugging in your new guess into the formula) and get closer approximations for your root. Eventually you have a "new guess" that makes f(new guess) really, really close to zero -- it's a root! (Or close enough for government work, as they say).</p>

<p>In our case, we want the inverse square function. Let's say we have a number <img src="https://betterexplained.com/latex/df072eb181107ba92096.png" alt="$i$" width="7" height="13" style="vertical-align:-0.2px" class="bex-math"></img> (that's all we start with, right?) and want to find the inverse square root: <img src="https://betterexplained.com/latex/e1dbf2e47e2dc6b0838f.png" alt="$1/\sqrt{i}$" width="40" height="22" style="vertical-align:-4.53px" class="bex-math"></img>. If we make a guess "x" as the inverse root, the error between our original number and our guess "x" is:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/29a9df8c26eb2808be1fec9e75120d7c.png' width='137' height='38' alt='\displaystyle{\text{error}(x) = \frac{1}{x^2} - i}' class='tex'></p>

<p>This is because x is roughly <img src="https://betterexplained.com/latex/e1dbf2e47e2dc6b0838f.png" alt="$1/\sqrt{i}$" width="40" height="22" style="vertical-align:-4.53px" class="bex-math"></img>. If we square x we get <img src="https://betterexplained.com/latex/41ae9c78015689c81980.png" alt="$1/i$" width="25" height="19" style="vertical-align:-4.53px" class="bex-math"></img>, and if we take the inverse we should get something close to <img src="https://betterexplained.com/latex/df072eb181107ba92096.png" alt="$i$" width="7" height="13" style="vertical-align:-0.2px" class="bex-math"></img>. If we subtract these two values, we can find our error.</p>

<p>Clearly, we want to make our error as small as possible. That means finding the "x" that makes error(x) = 0, which is the same as finding the root of the error equation. If we plug error(x) into Newton's approximation formula:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/20dd1ccb23b1b716d3e473414d5a7558.png' width='197' height='44' alt='\displaystyle{\text{newguess} = g - \frac{\text{error}(g)}{\text{error}&#039;(g)}}' class='tex'></p>

<p>and take the proper derivatives:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/f72bec3b5d09c0d48f3db161d004e0bb.png' width='142' height='21' alt='\displaystyle{\text{error}(g)= g^{-2} - i}' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/0930b3df13fbdc72eda3c8c1564f26ff.png' width='140' height='21' alt='\displaystyle{\text{error}&#039;(g)= -2g^{-3}}' class='tex'></p>

<p>we can plug them in to get the formula for a better guess:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/2f55b56865f195449486964486822565.png' width='187' height='44' alt='\displaystyle{\text{newguess} = g - \frac{g^{-2} - i}{-2g^{-3}} }' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/74f0552403da3919f84fc12969fb6851.png' width='257' height='21' alt='\displaystyle{\text{newguess} = g - (-0.5g + 0.5ig^3) }' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/4309eed7a08c2392159077a76b91311d.png' width='196' height='21' alt='\displaystyle{\text{newguess} = 1.5g - 0.5ig^3}' class='tex'></p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/6727cb2d8e7d2a776621949520b347fc.png' width='211' height='21' alt='\displaystyle{\text{newguess} = g (1.5 - 0.5ig^2)}' class='tex'></p>

<p>Which is exactly the equation you see in the code above, remembering that x is our new guess (g) and "xhalf" is half of the original value (<img src="https://betterexplained.com/latex/55ddb956e26b4708a583.png" alt="$0.5 i$" width="30" height="13" style="vertical-align:-0.4px" class="bex-math"></img>):</p>

<p><code>x = x*(1.5f - xhalf*x*x);</code></p>

<p>With this formula, we can start with a guess "g" and repeat the formula to get better guesses. Try this demo for using multiple iterations to find the inverse square:</p>

<iframe src="https://instacalc.com/50175/embed" frameborder="0" marginwidth="0" marginheight="0" width="600" height="550"></iframe>

<p>In this demo, we start by guessing the square root is half the number: <img src="https://betterexplained.com/latex/aed183572fb94c010ae1.png" alt="$\sqrt{n} \sim \frac{n}{2}$" width="67" height="22" style="vertical-align:-6.25px" class="bex-math"></img>, which  means <img src="https://betterexplained.com/latex/aa06271d8427df5a9195.png" alt="$\frac{1}{\sqrt{n}} \sim \frac{2}{n}$" width="67" height="27" style="vertical-align:-10.67px" class="bex-math"></img>. Running a few rounds of Newton's Method quickly converges on the real result. (Try n=2, 4, 10, etc.)</p>

<p>So my friends, the question becomes: "How can we make a good initial guess?"</p>

<h2>Making a Good Guess</h2>

<p>What's a good guess for the inverse square root? It's a bit of a trick question -- our best guess for the inverse square root is the inverse square root itself!</p>

<p>Ok hotshot, you ask, how do we actually get <img src="https://betterexplained.com/latex/2bf4b1608fd53d024997.png" alt="$1/\sqrt{x}$" width="44" height="20" style="vertical-align:-4.53px" class="bex-math"></img>?</p>

<p>This is where the magic kicks in. Let's say you have a number in exponent form or scientific notation:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/e2712237d931382e134fe7e78755d219.png' width='119' height='17' alt='\displaystyle{10^6 = \text{1 million}}' class='tex'></p>

<p>Now, if you want to find the regular square root, you'd just divide the exponent by 2:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/423d702277f2534399efae0a207c8fcd.png' width='212' height='23' alt='\displaystyle{\sqrt{10^6} = 10^{\frac{6}{2}} = 10^3 = 1,000}' class='tex'></p>

<p>And if you want the <strong>inverse</strong> square root, divide the exponent by -2 to flip the sign:</p>

<p><img src='https://betterexplained.com/wp-content/plugins/wp-latexrender/pictures/20bd4b5194f209946e624978dcf5f6be.png' width='239' height='41' alt='\displaystyle{\frac{1}{\sqrt{10^6}} = 10^{\frac{6}{-2}} = 10^{-3} = \frac{1}{1,000}}' class='tex'></p>

<p>So, how can we get the exponent of a number without other expensive operations?</p>

<h2>Floats are stored in mantissa-exponent form</h2>

<p>Well, we're in luck. Floating-point numbers are stored by computers in mantissa-exponent form, so it's possible to extract and divide the exponent!</p>

<p>But instead of explicitly doing division (expensive for the CPU), the code uses another clever hack: it shifts bits. Right-shifting by one position is the same as dividing by two (<a href="http://instacalc.com/20277">you can try this for any power of 2</a>, but it will truncate the remainder). And if you want to get a negative number, instead of multiplying by -1 (multiplications are expensive), just subtract the number from "0" (subtractions are cheap).</p>

<p>So, the code converts the floating-point number into an integer. It then shifts the bits by one, which means the exponent bits are divided by 2 (when we eventually turn the bits back into a float). And lastly, to negate the exponent, we subtract from the magic number 0x5f3759df. This does a few things: it preserves the mantissa (the non-exponent part, aka 5 in: <img src="https://betterexplained.com/latex/1ef1de9eafe0618e2690.png" alt="$5 \cdot 10^6$" width="49" height="17" style="vertical-align:-0.4px" class="bex-math"></img>), handles odd-even exponents, shifting bits from the exponent <em>into</em> the mantissa, and all sorts of funky stuff. The paper has more details and explanation, I didn't catch all of it the first time around. As always, feel free to comment if you have a better explanation of what's happening.</p>

<p>The result is that we get an initial guess that is really close to the real inverse square root! We can then do a single round of Newton's method to refine the guess. More rounds are possible (at an additional computational expense), but one round is all that's needed for the precision needed.</p>

<h2>So, why the magic number?</h2>

<p>The great hack is how integers and floating-point numbers are stored. Floating-point numbers like <img src="https://betterexplained.com/latex/dd8990441211fc29e427.png" alt="$5.4 \cdot 10^6$" width="63" height="17" style="vertical-align:-0.4px" class="bex-math"></img> store their exponent in a separate range of bits than "5.4". When you shift the entire number, you divide the exponent by 2, as well as dividing the number (5.4) by 2 as well. This is where the magic number comes in -- it does some cool corrections for this division, that I don't quite understand. However, there are several magic numbers that could be used -- this one happens to minimize the error in the mantissa.</p>

<p>The magic number also corrects for even/odd exponents; <a href="http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf">the paper</a> mentions you can also find other magic numbers to use.</p>

<h2>Resources</h2>

<p>There's further discussion on reddit (user pb_zeppelin) and slashdot:</p>

<ul>
<li><a href="http://programming.reddit.com/info/t9zb/comments">http://programming.reddit.com/info/t9zb/comments</a></li>
<li><a href="http://games.slashdot.org/article.pl?sid=06%2F12%2F01%2F184205">http://games.slashdot.org/article.pl?sid=06/12/01/184205</a> and <a href="http://games.slashdot.org/comments.pl?sid=209372&amp;%23038;cid=17077640">my comment</a></li>
</ul>

]]></content:encoded>
					
					<wfw:commentRss>https://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/feed/</wfw:commentRss>
			<slash:comments>35</slash:comments>
		

			</item>
	<item>
		<title>Swap two variables using XOR</title>
		<link>https://betterexplained.com/articles/swap-two-variables-using-xor/</link>
					<comments>https://betterexplained.com/articles/swap-two-variables-using-xor/#disqus_thread</comments>
		
		<dc:creator><![CDATA[kalid]]></dc:creator>
		<pubDate>Tue, 16 Jan 2007 20:00:40 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://betterexplained.com/articles/swap-two-variables-using-xor/</guid>

					<description><![CDATA[Most people would swap two variables x and y using a temporary variable, like this: tmp = x x = y y = tmp Here’s a neat programming trick to swap two values without needing a temp: x = x xor y y = x xor y x = x xor y Don’t believe me? [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Most people would swap two variables x and y using a temporary variable, like this:</p>

<pre><code>tmp = x
x = y
y = tmp
</code></pre>

<p>Here’s a neat programming trick to swap two values without needing a temp:</p>

<pre><code>x = x xor y
y = x xor y
x = x xor y
</code></pre>

<p>Don’t believe me? Try it out – write in any initial value for x and y:</p>

<iframe src="https://instacalc.com/56317/embed" frameborder="0" marginwidth="0" marginheight="0" width="450" height="410"></iframe>

<p>It almost seems like magic – the same statement is repeated 3 times and <em>voila</em> – the values magically swap? Let’s take a closer look.</p>

<h2>How it works</h2>

<p>To understand this trick, break the statements into unique values:</p>

<pre><code>x1 = x xor y
y1 = x1 xor y
x2 = x1 xor y1
</code></pre>

<p>According to our code, x2 should have y’s original value. Let’s work out the details for the last step:</p>

<pre><code>x2 = x1 xor y1
x2 = x1 xor (x1 xor y)   // replace y1
x2 = (x1 xor x1) xor y   // regroup parenthesis - order does not matter for XOR
x2 = 0 xor y             // a xor a =&gt; 0
x2 = y                   // 0 xor a =&gt; a; x2 now has y's original value
</code></pre>

<p>Wow – x2 really does equal y! The swap happened. Now let’s try it out for y1:</p>

<pre><code>y1 = x1 xor y
y1 = (x xor y) xor y
y1 = x xor (y xor y)
y1 = x xor 0
y1 = x                  // y1 == x's original value
</code></pre>

<p>And tada the trick worked again. x2 and y1 have the swapped answers.</p>

<h2>Intuitive Understanding</h2>

<p>Ok, sure, the boolean algebra works out great — but that’s not satisfying. I want to <strong>understand</strong> it deep down and have it make sense, not be some artifact of the properties of XOR. Let’s take another look:</p>

<pre><code>1:   x = x xor y
2:   y = x xor y
3:   x = x xor y
</code></pre>

<p>On line 1 we combine x and y (using XOR) to get this “hybrid” and we store it back in x. XOR is a great way to save information, because you can remove it by doing an XOR again.</p>

<p>So, this is exactly what we do on line 2&#46; We XOR the hybrid with y, which cancels out all the y information, leaving us only with x. We save this result back into y, so now they have swapped.</p>

<p>On the last line, x still has the hybrid value. We XOR it yet again with y (now with x’s original value) to remove all traces of x out of the hybrid. This leaves us with y, and the swap is complete!</p>

<h2>Would you really use this?</h2>

<p>No way. This is a cool trick, but don’t write this as an actual swap function. If you have to debug it in 6 months you’ll be in for some fun. Let me show you why:</p>

<p>Suppose x and y are pointers or references to objects, and both point to the same location. We’d expect our swapping function to just switch the values around, with no net change, right?</p>

<p>Well, take a look at what happens if we expand out line 1:</p>

<pre><code>x = x xor y
x = x xor x  // x and y are equal
x = 0
</code></pre>

<p>Wow! So x becomes 0 right at the get-go. That’s ok by itself, but because x and y are at the same location, we just made y zero as well! We’ve lost the original values, a problem known as <a href="https://en.wikipedia.org/wiki/Aliasing_%28computing%29">aliasing</a>: changing one variable has an indirect effect on another.</p>

<p>So, would you have caught this bug? I wouldn’t have, and it would have been a nightmare figuring out why an innocuous swap function was causing data loss. Cute tricks like these can be pretty dangerous. As Brian Kernighan said:</p>

<blockquote>

<p>Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.</p>
</blockquote>

<p>This applies so well here – we wrote the code pretty much as cleverly as we could :). So, treat this as an intellectual exercise that brings up a few points:</p>

<ul>
<li>XOR is a great way to combine information and later extract it. XOR-based encryption uses this technique. Also, XOR can combine N items together, not just 2.</li>
<li>There are new ways to perform even the simplest operations.</li>
</ul>

<h2>Even more hairy details</h2>

<p>Now, how does this work on a CPU-level?</p>

<p>The computer actually has an implicit “temp” variable that stores intermediate results before writing them back to a register. For example, if you add 3 to a register (in machine-language pseudocode):</p>

<pre><code>ADD 3 A  // add 3 to register A
</code></pre>

<p>The <a href="https://en.wikipedia.org/wiki/Arithmetic_logic_unit">ALU</a> (Arithmetic Logic Unit) is actually what executes the instruction 3+A. It takes the inputs (3,A) and creates a result (3 + A), which the CPU then stores back into A’s original register. So, we used the ALU as temporary scratch space before we had the final answer.</p>

<p>We take the ALU’s implicit temporary data for granted, but it’s always there. In a similar way, the ALU can return the intermediate result of the XOR in the case of <code>x = x xor y</code>, at which point the CPU stores it into x’s original register.</p>

<p>Because we aren’t used to thinking about the poor, neglected ALU, the XOR swap seems magical because it doesn’t have an explicit temporary variable.  Some machines have a 1-step exchange XCHG instruction to swap two registers.</p>

<p>Further reading:</p>

<ul>
<li><a href="https://en.wikipedia.org/wiki/XOR_swap_algorithm">Wikipedia article on XOR swap</a></li>
</ul>

]]></content:encoded>
					
					<wfw:commentRss>https://betterexplained.com/articles/swap-two-variables-using-xor/feed/</wfw:commentRss>
			<slash:comments>42</slash:comments>
		

			</item>
	</channel>
</rss>
