<?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>y-less.com</title>
	<atom:link href="http://y-less.com/wordpress/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://y-less.com/wordpress</link>
	<description>Alex "Y_Less" Cole's blog</description>
	<lastBuildDate>Wed, 11 Aug 2010 17:09:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Mean Joke</title>
		<link>http://y-less.com/wordpress/?p=162</link>
		<comments>http://y-less.com/wordpress/?p=162#comments</comments>
		<pubDate>Wed, 11 Aug 2010 17:09:21 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=162</guid>
		<description><![CDATA[I&#8217;ve done this to a few people &#8211; it works well if you are with a fairly computer illiterate person on a windows computer. If they leave the room for a moment, don&#8217;t frape them &#8211; that&#8217;s frankly old and boring, do this instead: Open a command prompt (run->cmd). Type the following: color 97 help [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve done this to a few people &#8211; it works well if you are with a fairly computer illiterate person on a windows computer.  If they leave the room for a moment, don&#8217;t frape them &#8211; that&#8217;s frankly old and boring, do this instead:</p>
<p>Open a command prompt (run->cmd).<br />
Type the following:</p>
<p>color 97<br />
help for</p>
<p>Then press alt+enter.  This will give a full screen white on blue gibberish messge (or appear that way and first glance) &#8211; then sit back and wait for the horror as they &#8220;realise&#8221; their computer has got a BSOD.  Most people know enough about them to recognise them and know theyre bad, but not enough to be able to analyse the kernel dump messages.</p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=162</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Compile Time String Hashing 2</title>
		<link>http://y-less.com/wordpress/?p=138</link>
		<comments>http://y-less.com/wordpress/?p=138#comments</comments>
		<pubDate>Thu, 13 May 2010 19:29:34 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=138</guid>
		<description><![CDATA[Introduction Barely days after writing the first compile time hashing post, I needed to use the information in it. As I said at the time it&#8217;s ugly, and the Boost license raises some questions for its use in all locations, so I developed a better solution as a separate tool, giving the much nicer overall [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Barely days after writing the first compile time hashing post, I needed to use the information in it. As I said at the time it&#8217;s ugly, and the Boost license raises some questions for its use in all locations, so I developed a better solution as a separate tool, giving the much nicer overall syntax of:</p>
<pre class="brush: cpp;">#include &quot;file_ext.cth&quot;
switch (Hash(szInputString))
{
	case __H(hello):
		// Do something
	case __H(there):
		// Something else
	default:
		// Other
}</pre>
<p><span id="more-138"></span></p>
<h2>Use</h2>
<p>To use this in code is very simple. Define the string that you want to hash inside a __H macro, like so:</p>
<pre class="brush: cpp;">__H(HASH_THIS)</pre>
<p>Then, above this point, include another file (which may well not exist yet) whose file name is:</p>
<pre class="brush: plain;">CurrentFileName_CurrentFileExtension.cth</pre>
<p>So the inclusion for a file &#8220;main.cpp&#8221; would be &#8220;main_cpp.cth&#8221; (cth stands for &#8220;Compile Time Hashing&#8221; if you&#8217;re wondering) (this technique is based on that used for WPP &#8211; Windows Software Trace Preprocessor). If you don&#8217;t like using __H you will have to change it in the source code of the tool (and that&#8217;s not as trivial as it sounds, I&#8217;ve written it as a very efficient, but somewhat obfuscated, state machine).</p>
<p>You also need to include a single file with the actual definition of the hash function (currently <a href="http://www.burtleburtle.net/bob/hash/doobs.html">Bernstein</a> as it is fast and has low collisions) into your project.</p>
<p>The final stage is calling the hash program on the current file, like so:</p>
<pre class="brush: plain;">c:\path\to\file&gt; &quot;c:\path\to\tool\StringHashing.exe&quot; (filename) (ext)</pre>
<h2>Collisions</h2>
<p>If you have two strings in the same file (yes, sorry &#8211; see the limitations section) with the same hash the compiler will generate an error. This error is currently not much help as it only tells you the second string with this hash. I did try to make it give you both but apparently macros aren&#8217;t evaluated in &#8220;#error&#8221;.</p>
<h2>Automation</h2>
<p>The tool itself has no capability for looping through directories &#8211; you simply call it passing the name and extension of a single file, however for real use I have integrated it in to my build process in Visual Studio using a batch file to automate the calling.</p>
<p>To call the tool, add a pre-build event something like the following. Obviously it depends on the location of your tool &#8211; I have a very strict (and, IMHO, neat) VS solution directory layout, so things like this are in a &#8220;Tools&#8221; directory:</p>
<pre class="brush: plain;">&quot;$(SolutionDir)\Tools\StringHash.bat&quot; &quot;$(ProjectDir)&quot;</pre>
<p>The batch file itself that I use is:</p>
<pre class="brush: bash;">@echo off
setlocal

if '%1' == '' echo Usage:  StringHash.bat [Directory]

set HASH_DIR=%~dp0

echo &quot;Scanning for .cpp files.&quot;
for /f &quot;usebackq delims=&quot; %%i in (`dir /s /b &quot;%~1\*.cpp&quot;`) do call :dohash &quot;%%i&quot;
cd %HASH_DIR%
echo &quot;Scanning for .c files.&quot;
for /f &quot;usebackq delims=&quot; %%i in (`dir /s /b &quot;%~1\*.c&quot;`) do call :dohash &quot;%%i&quot;
cd %HASH_DIR%
echo &quot;Scanning for .h files.&quot;
for /f &quot;usebackq delims=&quot; %%i in (`dir /s /b &quot;%~1\*.h&quot;`) do call :dohash &quot;%%i&quot;
cd %HASH_DIR%
echo &quot;Scanning for .hpp files.&quot;
for /f &quot;usebackq delims=&quot; %%i in (`dir /s /b &quot;%~1\*.hpp&quot;`) do call :dohash &quot;%%i&quot;
cd %HASH_DIR%
echo &quot;Scanning for .def files.&quot;
for /f &quot;usebackq delims=&quot; %%i in (`dir /s /b &quot;%~1\*.def&quot;`) do call :dohash &quot;%%i&quot;
cd %HASH_DIR%
goto :EOF

:dohash
cd &quot;%~p1&quot;
&quot;%HASH_DIR%\StringHashing.exe&quot; %~n1 %~x1

goto :EOF</pre>
<p>This will do all .cpp, .c, .hpp, .h and .def files with any __H appearences (technically it does them all regardless, but if you don&#8217;t include the extra files they don&#8217;t matter).</p>
<h2>Limitations</h2>
<h3>Stupid</h3>
<p>I wrote, tested, integrated and automated this tool inside about an hour, and have only modified it once since, so it is VERY simple and VERY stupid. If it sees the pattern &#8220;__H(TEXT)&#8221; it will convert it &#8211; regardless of other concerns such as current comment or string context. For this reason you have to be VERY careful when doing something like:</p>
<pre class="brush: cpp;">// The &quot;__H(hello)&quot; macro evaluates to &quot;__H_hello&quot;.
case __H(hello):</pre>
<p>This code has the required pattern &#8220;__H(TEXT)&#8221; TWICE &#8211; the one in comments counts, so the tool will parse both then detect a collision between the two. Stick to code like:</p>
<pre class="brush: cpp;">// The &quot;__H&quot; macro evaluates to &quot;__H_hello&quot;.
case __H(hello):</pre>
<h3>Characters</h3>
<p>Only characters valid in C symbol names may be used in the text within the brackets, unlike symbol names however numbers may be the first (and only) characters. The switch is also case sensitive.</p>
<h3>File Scope</h3>
<p>The parser generates ONE inclusion per file, so this is invalid code, despite looking fine:</p>
<pre class="brush: cpp;">#include &quot;main_cpp.cth&quot;
switch (Hash(a))
{
	case __H(hello):
		break;
}
switch (Hash(b))
{
	case __H(hello):
		break;
}</pre>
<p>However, there are ways around this problem, but they&#8217;re ugly:</p>
<pre class="brush: cpp;">// Include the hashes.
#include &quot;main_cpp.cth&quot;
// Redefine the macros (see &quot;advanced&quot; for wierd syntax).
#undef __H
#define __H(\
	m)
#define HASH(m) __H_##m
// Generate all the hashes in valid code.
__H(hello)
__H(hi)
// Now use the hashes.
switch (Hash(a))
{
	case HASH(hello):
		break;
}
switch (Hash(b))
{
	case HASH(hello):
		break;
}</pre>
<p>That undefines the __H macro so that appearences of it in code will not generate any code that the compiler will see. It then defines a new macro to the old definition of __H so that you can still use the hashes, and use them multiple times. Finally it includes all the &#8220;__H(TEXT)&#8221; macros ONCE so that the will not collide.</p>
<p>The alternate method is using the syntax from the advanced section:</p>
<pre class="brush: cpp;">#include &quot;main_cpp.cth&quot;
switch (Hash(a))
{
	case __H(hello):
		break;
}
switch (Hash(b))
{
	case __H(\
		hello):
		break;
}</pre>
<h2>Advanced</h2>
<h3>Spacing</h3>
<p>Note that despite being quite stupid, the tool does have the ability to recognise different spacings, so if you want spaces before or after your brackets on the &#8220;__H&#8221;, you can do.</p>
<h3>Overriding</h3>
<p>If for some reason you need to override the &#8220;__H&#8221; macro, or use it&#8217;s syntax without being parsed by the tool (as in the previous example) you can use the line continuation operator to write valid code without the tool picking it up:</p>
<pre class="brush: cpp;">switch (Hash(b))
{
	case __H(\
		hello):
		break;
}</pre>
<p>This will be correctly interpreted by the compiler, but it ignored by the tool. I mentioned that I have only modified the tool once, and this is why. Originally this code did work and was ignored by the tool, but it complained about a bad macro format, so I added code to ignore just this case quietly.</p>
<h2>Linux/Non-VS</h2>
<p>I have not written anything for any of these systems. The tool was written in as close to pure C as I could manage to quickly knock out off the top of my head with no checking, so should recompile. I have no doubt Perl and possibly Python would be vastly better for this on Linux (and Windows if you have it on there), but I&#8217;ve written the code now so it&#8217;s a moot point. I don&#8217;t know how to integrate calling the tool into other tool chains, but I can&#8217;t see it being hard if they&#8217;re any good at all.</p>
<h2>Download</h2>
<p>I have included a VS solution with both the tool&#8217;s project and an example project using said tool <a href="http://www.y-less.com/random/CTH.zip">here</a></p>
<h2>Footnote</h2>
<p>I just installed <a href="http://www.deanlee.cn/wordpress/code_highlighter_plugin_for_wordpress/">this</a> syntax highligher as my code was VERY hard to read on here. Hopefully it will be better now. Next step &#8211; a decent theme&#8230;</p>
<p>Update: I changed to <a href="http://en.support.wordpress.com/code/posting-source-code/">this</a> highlighter &#8211; it&#8217;s much nicer.</p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=138</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ Compile-Time String Hashing</title>
		<link>http://y-less.com/wordpress/?p=133</link>
		<comments>http://y-less.com/wordpress/?p=133#comments</comments>
		<pubDate>Thu, 06 May 2010 14:40:36 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=133</guid>
		<description><![CDATA[This is something that I have been interested in for a while. As people may know, in C++ you can&#8217;t do: switch (szInputString) { case &#34;hello&#34;: // Do something case &#34;there&#34;: // Something else default: // Other } This has always seemed quite an arbitrary limitation to me, especially given that it would not be [...]]]></description>
			<content:encoded><![CDATA[<p>This is something that I have been interested in for a while.  As people may know, in C++ you can&#8217;t do:</p>
<pre class="brush: cpp;">switch (szInputString)
{
	case &quot;hello&quot;:
		// Do something
	case &quot;there&quot;:
		// Something else
	default:
		// Other
}</pre>
<p>This has always seemed quite an arbitrary limitation to me, especially given that it would not be hard &#8211; all you need is a standard hash function to convert the strings to unique numbers in both code and the compiler.<span id="more-133"></span>  The compiler can then generate the following (the only problem comes from collisions on inputs):</p>
<pre class="brush: cpp;">switch (hash(szInputString))
{
	case HASH(&quot;hello&quot;):
		// Do something
	case HASH(&quot;there&quot;):
		// Something else
	default:
		// Other
}</pre>
<p>I just happened upon a method of doing this today so I had to post it!  It&#8217;s pretty ugly and limited, but it&#8217;s an improvement over the current situation:<br />
<a href="http://lists.boost.org/Archives/boost/2003/01/42388.php">boost compile time string hashing</a><br />
As I said it&#8217;s ugly, and I&#8217;m not lying:</p>
<pre class="brush: cpp;">switch (hash_of(szInputString))
{
	case Compile&lt;'h', 'e', 'l', 'l', 'o'&gt;::hash:
		// Do something
	case Compile&lt;'t', 'h', 'e', 'r', 'e'&gt;::hash:
		// Something else
	default:
		// Other
}</pre>
<p>But this can be improved upon slightly:</p>
<pre class="brush: cpp;">#define HASH(...) \
	Compile&amp;lt;__VA_ARGS__&amp;gt;::hash

switch (hash_of(szInputString))
{
	case HASH('h','e','l','l','o'):
		// Do something
	case HASH('t','h','e','r','e'):
		// Something else
	default:
		// Other
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=133</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Even more distance check optimisations &#8211; Updated</title>
		<link>http://y-less.com/wordpress/?p=122</link>
		<comments>http://y-less.com/wordpress/?p=122#comments</comments>
		<pubDate>Wed, 05 May 2010 18:24:04 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=122</guid>
		<description><![CDATA[Okay, since my last post on this topic I have been doing more work in this area and have further refined my codes. Basically, I made the realisation that if you have two static items and want the distance to both from a point, you don&#8217;t need to calculate them both. If the two points [...]]]></description>
			<content:encoded><![CDATA[<p>Okay, since my last post on this topic I have been doing more work in this area and have further refined my codes. Basically, I made the realisation that if you have two static items and want the distance to both from a point, you don&#8217;t need to calculate them both. If the two points are always static (or move infrequently) then you can easilly store the distance between them statically (or, rather, you can store a value which is a function of the distance between them). If you know the distance from the point to the first item, and the distance between the items, it is very easy to get the distance to the second item.<br />
<span id="more-122"></span></p>
<h2>Maths</h2>
<p>First, the maths. Let&#8217;s assume there are two objects, A and B, and a point P. The distance between A and P and B and P are then:<br />
<code><br />
Dpa = sqrt( (Px - Ax)^2 + (Py - Ay)^2 + (Pz - Az)^2 )<br />
Dpb = sqrt( (Px - Bx)^2 + (Py - By)^2 + (Pz - Bz)^2 )<br />
</code><br />
This is basic and was covered in the last post.<br />
It is obvious that:<br />
<code><br />
Bx = Ax + (Bx - Ax)<br />
</code><br />
If you don&#8217;t believe me, rearrange the formula and A will disappear.<br />
So we can now get:<br />
<code><br />
Dpa = sqrt( (Px - Ax)^2 + (Py - Ay)^2 + (Pz - Az)^2 )<br />
Dpb = sqrt( (Px - (Ax + (Bx - Ax)))^2 + (Py - (Ay + (By - Ay)))^2 + (Pz - (Az + (Bz - Az)))^2 )<br />
</code><br />
I will rearrange one of these sections, the x, y and z parts are all identical:<br />
<code><br />
X = (Px - Bx)^2</p>
<p>X = (Px - (Ax + (Bx - Ax)))^2</p>
<p>X = (Px - Ax - Bx + Ax)^2</p>
<p>X = (Px - Ax + (Ax - Bx))^2</p>
<p>t = (Ax - Bx)<br />
X = (Px - Ax + t)^2</p>
<p>X = (Px - Ax + t)(Px - Ax + t)</p>
<p>X = Px^2 - 2PxAx + Ax^2 + 2tPx - 2tAx + t^2</p>
<p>X = (Px - Ax)^2 + (t^2 - 2tAx) + 2tPx</p>
<p>X = (Px - Ax)^2 + ((Ax - Bx)^2 - 2Ax(Ax - Bx)) + Px(2(Ax - Bx))<br />
</code><br />
So what does this prove? Well we started with the equation for the distance between P and B, and ended up with the equation between P and A with some extra bits. These extra bits look complicated and wierd, but they are actually very simple. Firstly:<br />
<code><br />
(Ax - Bx)^2 - 2Ax(Ax - Bx)<br />
</code><br />
That ONLY contains A and B, which are static objects, so this number is a constant for two items! What&#8217;s more, this is a constant for X, Y and Z, so these can all be combined in to a single value. Secondly:<br />
<code><br />
Px(2(Ax - Bx))<br />
</code><br />
Here, P is used, which is our dynamic position, but the rest of it is also a constant for two objects. So we can make out final equation:<br />
<code><br />
Dpb = Dpa + Cab + PxABX + PyABy + PzABz<br />
</code><br />
This excludes the square root action, but that&#8217;s often not needed.</p>
<h2>Use</h2>
<p>If, as is often the case, you wish to compare one point (P) to a large collection of other points (A, B, C etc), and those other points are all known in advance, you can use this method to pre-compute certain values.  This is best demonstrated with a code example:</p>
<pre class="brush: cpp;">struct obj
{
	objinfo info;
	float x, y, z;
	float ow;
	float ox, oy, oz;
};

struct obj g_objects[10];

int g_count = -1;

// This function very basically adds a new object to the array.
void AddObj(float x, float y, float z)
{
	float ox, oy, oz;
	// Get the offset from the last object.
	if (g_count == -1)
	{
		ox = 0.0f;
		oy = 0.0f;
		oz = 0.0f;
	}
	else
	{
		dx = g_objects[g_count].x;
		dy = g_objects[g_count].y;
		dz = g_objects[g_count].z;
	}
	float
		dx = ox - x,
		dy = oy - y,
		dz = oz - z;
	++g_count;
	// Store the offsets.
	g_objects[g_count].ox = 2 * dx;
	g_objects[g_count].oy = 2 * dy;
	g_objects[g_count].oz = 2 * dz;
	// Calculate the main constant.
	g_objects[g_count].ow =
		(dx * dx + dy * dy + dz * dz) - 2 *
		(ox * dx + oy * dy + oz * dz);
	// Store the other data.
	g_objects[g_count].x = x;
	g_objects[g_count].y = y;
	g_objects[g_count].z = z;
}

// This function takes a position and checks which objects are in range.
void CheckAll(float x, float y, float z, float range)
{
	float
		offset = x * x + y * y + z * z;
	struct obj *
		cur = g_objects;
	for (int i = 0; i &lt;= g_count; ++i)
	{
		// Calculate the distance to the object.
		offset = offset + cur.ow + x * cur.ox + y * cur.oy + z * cur.oz;
		// We now have the SQUARED distance to this object.
		if (offset &lt; range * range)
		{
			printf(&quot;This object is in range&quot;);
		}
		++cur;
	}
}</pre>
<h2>Future</h2>
<p>I am trying to determine wether the dot-product can be optimised (if you were to write custom assembler there it would be awesome), but I don&#8217;t know if it is possible to use some method so that all those multiplies in the inner loop can be combined.  For reference, this is the dot product:<br />
<code><br />
PxABX + PyABy + PzABz<br />
</code><br />
If something can be done with that the code will become:<br />
<code><br />
Distance = Last Distance + Constant + Dot Product<br />
</code></p>
<h2>Conclusion</h2>
<p>I intend to use this somehow, I already use a version of this code in my current research and it has HALVED the time taken for my code to run &#8211; so that has to be a good thing!</p>
<h2>Update</h2>
<p>There is some interesting information here:<br />
<a href="http://www.bealto.com/mp-dot_intro.html">How fast can we compute the dot product?</a><br />
I decided to look into the SSE stuff to help this out.  The good thing is that we can combine the Constant in to the dot product to by adding a W component of 1 to the Point&#8217;s vector &#8211; this will mean that both position and offset can be stored as SSE 128bit values in the structure.  It will require some very tricky coding to actually be able to use this information and frankly I&#8217;m not sure any greater improvement is worth it, especially not the code to interleave the calculations &#8211; especially given the amount of other stuff any function using this data will need to do.</p>
<p>This code would also restrict who can use the code based on SSE availability.</p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=122</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Distance check optimisations</title>
		<link>http://y-less.com/wordpress/?p=117</link>
		<comments>http://y-less.com/wordpress/?p=117#comments</comments>
		<pubDate>Mon, 26 Apr 2010 12:34:43 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=117</guid>
		<description><![CDATA[Pythagoras&#8217; rule is used to calculate the distance between two points in space (in any number of dimensions). In a lot of use cases in computing a very large number of points are compared at once, leading to many repeated applications of pythagoras. The computational compexity of every one of these calculations can be reduced [...]]]></description>
			<content:encoded><![CDATA[<p>Pythagoras&#8217; rule is used to calculate the distance between two points in space (in any number of dimensions). In a lot of use cases in computing a very large number of points are compared at once, leading to many repeated applications of pythagoras. The computational compexity of every one of these calculations can be reduced by a simple rearrangement to get pre-computed per-point constants. This method reduces both temporary variables and complex operations form every pair of points, at an expense of additional calculations for every individual point (usually a good trade off except in very small sets).</p>
<p>I&#8217;ve never seen this detailed anywhere else, though it likely has been, so I&#8217;m going over it here as a semi-official location.<br />
<span id="more-117"></span><br />
When getting the distance between two points, you use pythagoras (or a generalisation in many dimensions). The regular formula is:<br />
<code><br />
distance = sqrt ( (x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2 )<br />
</code><br />
With:<br />
<code><br />
position1 = x1, y1, z1<br />
position2 = x2, y2, z2<br />
</code><br />
This formula is perfectly fine if you just want the distance between two points. But what about when you have a huge number of points? One common use case I have come accross is where you have two sets of points and you want the distances between everything in the first set and everything in the second set. In a multiplayer object system there may be 100 players and 10,000 objects &#8211; that&#8217;s 1,000,000 calculations. Or in a molecular visualisation system could could have a grid of size 500&#215;500 with 200 atoms randomly spread &#8211; to calculate the effect of every atom on every grid point would require 50,000,000 calculations!</p>
<p>Obviously in standard pythagorean calculations the square root is the slow part, but for many applications this can be moved or removed entirely (for example checking if two objects are within a certain radius of each other can use the square of the radius for comparison instead). But when you&#8217;re talking on the order of millions of calculations, any improvement will be very useful!</p>
<p>A simple rearrangement follows:<br />
<code><br />
distance = sqrt ( (x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2 )<br />
distance^2 = (x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2<br />
distance^2 = x1^2 + x2^2 - 2x1x2 + y1^2 + y2^2 - 2y1y2 + z1^2 + z2^2 - 2z1z2<br />
distance^2 = x1^2 + y1^2 + z1^2 + x2^2 + y2^2 + z2^2 - 2x1x2 - 2y1y2 - 2z1z2<br />
distance^2 = (x1^2 + y1^2 + z1^2) + (x2^2 + y2^2 + z2^2) - 2(x1x2 + y1y2 + z1z2)<br />
distance = sqrt ( c1 + c2 - 2(x1x2 + y1y2 + z1z2) )<br />
</code><br />
Where:<br />
<code><br />
c1 = x1^2 + y1^2 + z1^2<br />
c2 = x2^2 + y2^2 + z2^2<br />
</code><br />
It should now be fairly obvious where this is going.  For any point (x, y, z), clearly (x^2, y^2, z^2) is a constant, so can be precomputed and stored &#8211; saving operations for every point combination.</p>
<p>If you will only be doing distance comparisons, for which the exact distance is not required, this can be optimised further.  To compare two distances, the squares can be compared to give the correct result, futher, half the squares compared will still give the correct result.  This gives:<br />
<code><br />
distance^2 / 2 = c1 + c2 - x1x2 - y1y2 - z1z2<br />
</code><br />
Where:<br />
<code><br />
c1 = (x1^2 + y1^2 + z1^2) / 2<br />
c2 = (x2^2 + y2^2 + z2^2) / 2<br />
</code><br />
Now the only calculation performed differently for every point pair is the end subtracted multiplications.</p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=117</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>LaTeX auto-processing</title>
		<link>http://y-less.com/wordpress/?p=96</link>
		<comments>http://y-less.com/wordpress/?p=96#comments</comments>
		<pubDate>Sun, 17 Jan 2010 17:03:39 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=96</guid>
		<description><![CDATA[During the course of my EngD I have started using LaTeX for writing papers and documents (technically I use MikTeX, but that&#8217;s just because I&#8217;m on Windows). It&#8217;s a bit tricky to get used to, especially as it does some things in an odd way, so I&#8217;ve written a handy little script to automate everything. [...]]]></description>
			<content:encoded><![CDATA[<p>During the course of my EngD I have started using <a href="http://www.latex-project.org/">LaTeX</a> for writing papers and documents (technically I use MikTeX, but that&#8217;s just because I&#8217;m on Windows).  It&#8217;s a bit tricky to get used to, especially as it does some things in an odd way, so I&#8217;ve written a handy little script to automate everything.<br />
<span id="more-96"></span><br />
Firstly the script &#8220;compile.bat&#8221;:</p>
<pre class="brush: bash;">:: %1 - Path
:: %2 - Filename

::D:

cd &quot;%1&quot;

mkdir %2

:: Set a load of basic variables to make commands easier.
set aux=
::-aux-directory=&quot;%1\auxfiles&quot;
set job=-job-name &quot;%1\%2\%2&quot;
set inc=-include-directory &quot;C:\Documents and Settings\&amp;lt;User&amp;gt;\Application Data\MiKTeX\fuzz&quot;
set src=-src-specials

:: Convert all local .PNG files to .EPS files for easy insertion.  Ideally this
:: would only convert images which have not already been converted, but I can't
:: see how to do that easily with ImageMagick, and that does preclude the
:: possibility of changing images and getting the new versions.  UPDATE:  I now
:: move all the .PNG files to the working directory after converting them.
:: This means they still exist for editing and you can update the .EPS file by
:: copying the .PNG back to the main directory but means that images are
:: generally only converted once each.
&quot;C:\Program Files\ImageMagick-6.5.9-Q16\mogrify.exe&quot; -format eps *.png

:: Move all the .PNG files to the working directory.
move /Y *.png %2

:: Compile the first pass in LaTeX.
:: Make sure all output files go to the same place and all input files are
:: searched for in the same place.
&quot;C:\Program Files\MiKTeX 2.8\miktex\bin\latex.exe&quot; %job% %aux% %inc% %src% &quot;%1\%2&quot;

:: Compile the references in BiBTeX.
&quot;C:\Program Files\MiKTeX 2.8\miktex\bin\bibtex.exe&quot; %aux% %inc% &quot;%1\%2&quot;

:: Run LaTeX twice more (who knows why...).
&quot;C:\Program Files\MiKTeX 2.8\miktex\bin\latex.exe&quot; %job% %aux% %inc% %src% &quot;%1\%2&quot;
&quot;C:\Program Files\MiKTeX 2.8\miktex\bin\latex.exe&quot; %job% %aux% %inc% %src% &quot;%1\%2&quot;

:: Create the PDF file.
::&quot;C:\Program Files\MiKTeX 2.8\miktex\bin\pdflatex.exe&quot; %job% %aux% %inc% &quot;%1\%2&quot;

:: Create a postscript file.
&quot;C:\Program Files\MiKTeX 2.8\miktex\bin\dvips.exe&quot; -Ppdf -o &quot;%1\%2\%2.ps&quot; &quot;%1\%2\%2.dvi&quot;

:: Convert to a PDF.
&quot;C:\Program Files\MiKTeX 2.8\miktex\bin\ps2pdf.exe&quot; &quot;%1\%2\%2.ps&quot; &quot;%1\%2.pdf&quot;

:: View it.
&quot;%1\%2.pdf&quot;</pre>
<p>Most of the lines are commented, but I&#8217;ll go over what it does anyway.</p>
<p>Firstly it reads the directory with your .tex file in and converts all found .PNGs to .EPS, this is because LaTeX can&#8217;t use PNGs but I tend to make them.  It then moves all the original PNGs to a child directory with the same name as the output file.  This allows you to modify the files and reconvert them by putting them back in the parent directory, but saves reconverting the files every time you produce output.</p>
<p>Secondly it generates the .DVI file.  There are quite a few lines to this as it is designed to work with Bibliotex, which requires multiple passes over a file to first collect and then fill out the required references.</p>
<p>Finally it generates a .PDF file and opens it for viewing.  You could just use the normal DVI viewer, but I don&#8217;t.</p>
<p>Note that this is written specifically for my use with the &#8220;FUZZ&#8221; type, if you don&#8217;t want to use this remove the include line.  If you do, update the &#8220;&lt;User&gt;&#8221; part.</p>
<p>I also use Notepad++, in which I have configured &#8220;alt+shift+m&#8221; to run this command using:</p>
<p><code><br />
"C:\Documents and Settings\&lt;User&gt;\Application Data\MiKTeX\compile.bat" $(CURRENT_DIRECTORY) $(NAME_PART)<br />
</code></p>
<p>Again, adjust &lt;User&gt; to your user name.</p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=96</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>el-mo.org</title>
		<link>http://y-less.com/wordpress/?p=95</link>
		<comments>http://y-less.com/wordpress/?p=95#comments</comments>
		<pubDate>Tue, 11 Aug 2009 00:29:18 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=95</guid>
		<description><![CDATA[http://www.el-mo.org/ has just been released &#8211; the latest site in the rapidly expanding (or not) y-less.com network. It&#8217;s just a basic homepage for my friend&#8217;s baby and entirely unmaintained &#8211; it was just made after a chat with him.]]></description>
			<content:encoded><![CDATA[<p>http://www.el-mo.org/ has just been released &#8211; the latest site in the rapidly expanding (or not) y-less.com network.  It&#8217;s just a basic homepage for my friend&#8217;s baby and entirely unmaintained &#8211; it was just made after a chat with him.</p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=95</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>yavascript.org</title>
		<link>http://y-less.com/wordpress/?p=89</link>
		<comments>http://y-less.com/wordpress/?p=89#comments</comments>
		<pubDate>Wed, 03 Jun 2009 21:02:37 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[release]]></category>
		<category><![CDATA[Site]]></category>
		<category><![CDATA[website]]></category>
		<category><![CDATA[yavascript]]></category>
		<category><![CDATA[yavascript.org]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=89</guid>
		<description><![CDATA[I have unofficially unveiled yavascript.org, by that I mean it&#8217;s on-line but this is the first public mention of it. It is fairly basic at the moment but has all the important information relating to the first version of my yavascript compiler and development system. So yeah, head on over and check it out, download [...]]]></description>
			<content:encoded><![CDATA[<p>I have unofficially unveiled <a href="http://yavascript.org/">yavascript.org</a>, by that I mean it&#8217;s on-line but this is the first public mention of it.  It is fairly basic at the moment but has all the important information relating to the first version of my yavascript compiler and development system.  So yeah, head on over and check it out, download and try out the tool and, if you&#8217;re so inclined, read my report on its development:</p>
<p><a href="http://yavascript.org/"><b>yavascript.org</b></a></p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=89</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>CSS showing off</title>
		<link>http://y-less.com/wordpress/?p=86</link>
		<comments>http://y-less.com/wordpress/?p=86#comments</comments>
		<pubDate>Wed, 03 Jun 2009 20:55:26 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[proof-of-concept]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=86</guid>
		<description><![CDATA[Recently I saw a question on a board I visit asking about how to make tooltips in Javascript, now I am a big JS fan, having spent a lot of time writing yavascript to aid in it&#8217;s development, but it&#8217;s a last resort &#8211; if you can&#8217;t do something any other way, use Javascript. Although [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I saw a question on a board I visit asking about how to make tooltips in Javascript, now I am a big JS fan, having spent a lot of time writing yavascript to aid in it&#8217;s development, but it&#8217;s a last resort &#8211; if you can&#8217;t do something any other way, use Javascript.  Although doing things such as tooltips without Javascript is admittedly hard and people may not even realise it&#8217;s possible &#8211; it is, so I did:</p>
<h2>Example 1 &#8211; CSS tooltips:</h2>
<p><a href="http://yavascript.org/css/tooltip.html">http://yavascript.org/css/tooltip.html</a></p>
<p>Note: CAN be dodgy in IE6 if  you don&#8217;t make the offset big enough to appear under the link.</p>
<h2>Example 2 &#8211; CSS lightbox:</h2>
<p><a href="http://yavascript.org/css/lightbox.html">http://yavascript.org/css/lightbox.html</a></p>
<p>Note: Currently only works in Firefox 3.</p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=86</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>yavascript debug mode</title>
		<link>http://y-less.com/wordpress/?p=82</link>
		<comments>http://y-less.com/wordpress/?p=82#comments</comments>
		<pubDate>Mon, 18 May 2009 10:59:16 +0000</pubDate>
		<dc:creator>Y_Less</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://y-less.com/wordpress/?p=82</guid>
		<description><![CDATA[Introduction One of the things added to the yavascript compiler, but not completed by the time I had to hand the project in to uni, was a debug mode. Because the compiler reads all the code in syntactically it can output it in whatever form it likes, including an experimental full debug mode. Basically your [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>One of the things added to the yavascript compiler, but not completed by the time I had to hand the project in to uni, was a debug mode.  Because the compiler reads all the code in syntactically it can output it in whatever form it likes, including an experimental full debug mode.  Basically your code goes from:</p>
<blockquote><pre>
a += /search/i;
</pre>
</blockquote>
<p>To:</p>
<blockquote><pre>
$Y._addAss(
	/* target */
	$Y._ref(
		/* name */
		'a',
		/* original code */
		'a',
		/* original line */
		42,
		/* original file */
		'my_code.js'),
	/* expression */
	$Y._regex(
		/* pattern */
		'search',
		/* modifiers */
		'i',
		/* original code */
		'/search/i',
		/* original line */
		43,
		/* original file */
		'my_code.js'),
	/* original code */
	'a +=\n\t/search/i;',
	/* original line */
	42,
	/* original file */
	'my_code.js');
</pre>
</blockquote>
<p>The obvious question is WHY?  But if you examine this code carefully you will see that it makes run-time debugging information a snap to collect and use to find problems.<br />
<span id="more-82"></span></p>
<h2>Use</h2>
<p>Given that this mode uses the compiler to generate it&#8217;s code, using this would be no more complicated than writing regular code and compiling, just compiling to a format different to minified code.  It could even be written to output all the required functions in the same file, though the more sensible option would be to get the user to include a second script in the html:</p>
<blockquote><pre>
&lt;script type="text/javascript" charset=”UTF-8” src="yavascript/debug.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" charset=”UTF-8” src="my_code_in_debug_mode.js"&gt;&lt;/script&gt;
</pre>
</blockquote>
<p>To compile in debug mode would simply require the addition of an extra command line switch &#8220;-d&#8221;, so to compile the following:</p>
<blockquote><pre>
var a = window['console'];
</pre>
</blockquote>
<p>In debug mode would require:</p>
<blockquote><pre>
yavascript.exe -f input_filename.ys -o output_filename.js -t web -d
</pre>
</blockquote>
<h2>_DEBUG</h2>
<p>The introduction of debug mode adds one of the most obvious uses of the preprocessor: debug outputs.  Although, given the verbose nature of the information output in debug mode, debug outputs will be less needed, there are still some things compilers can&#8217;t guess that you want to know.  Debug mode in the compiler and development mode in the browser (or other development environment) will both add an internal define called &#8220;_DEBUG&#8221; allowing code such as:</p>
<blockquote><pre>
a += 10;
#ifdef _DEBUG
	console.log('Did the addition at: ' + Date.now());
#endif
</pre>
</blockquote>
<p>That code will then be included or excluded depending on the compile mode, and included in development.</p>
<h2>Implementation</h2>
<p>Obviously using function calls instead of standard operators requires re-writing most of javascript with additional checks for things like null objects or missing and invalid properties.  One example for part of the addition function would be:</p>
<blockquote><pre>$Y =
	{
		toString :
			function (obj)
			{
				return Object.prototype.toString.call(obj);
			},
		isRegex :
			function (obj)
			{
				return this.toString(obj) === '[object RegExp]';
			},
		_add :
			function (first, second)
			{
				if (this.isRegex(first))
				{
					this.error('Can't add regular expressions:);
					this.error('first parameter: ' + first);
				}
				if (this.isRegex(second))
				{
					this.error('Can't add regular expressions:);
					this.error('second parameter: ' + second);
				}
				// Additional checks
				return first + second;
			}
	};
</pre>
</blockquote>
<p>Functions are prefixed with &#8216;_&#8217; to distinguish keywords from their debug equivalent, but this will probably be changed to something else.</p>
<p>Obviously far more checks than just regex can be included, such as trying to add an object to a number, or NaN to anything, but it&#8217;s just a short example.</p>
<h2>Bugs</h2>
<p>I&#8217;m still working on getting closures to work, but I have an idea for them.  Apart from that there aren&#8217;t any bugs as the system isn&#8217;t done yet!</p>
]]></content:encoded>
			<wfw:commentRss>http://y-less.com/wordpress/?feed=rss2&amp;p=82</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
