<?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"
	>

<channel>
	<title>gonium.net</title>
	<atom:link href="http://gonium.net/md/feed/" rel="self" type="application/rss+xml" />
	<link>http://gonium.net/md</link>
	<description>so much time, so little to do.</description>
	<pubDate>Sun, 23 Nov 2008 10:08:27 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.1</generator>
	<language>en</language>
			<item>
		<title>Installing Hoefler Text in LaTeX</title>
		<link>http://gonium.net/md/2008/11/23/installing-hoefler-text-in-latex/</link>
		<comments>http://gonium.net/md/2008/11/23/installing-hoefler-text-in-latex/#comments</comments>
		<pubDate>Sun, 23 Nov 2008 10:08:27 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[analog]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[font]]></category>

		<category><![CDATA[hoefler]]></category>

		<category><![CDATA[latex]]></category>

		<category><![CDATA[type]]></category>

		<category><![CDATA[typography]]></category>

		<guid isPermaLink="false">http://gonium.net/md/?p=113</guid>
		<description><![CDATA[
Not that straightforward, actually. Apple includes the Hoefler Text font in Mac OS X - its a really nice and readable professional font. Here&#8217;s what I did:

(1) You need to obtain the font in the opentype format (otf). Be careful: for me, the TTF version didn&#8217;t work. The Postscript type 1 version worked great.
(2) Use [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://gonium.net/md/wp-content/uploads/2008/11/3022406574_95c90e4667_o.png" alt="The Hoefler Text Ampersand" title="3022406574_95c90e4667_o" width="400" height="243" class="size-medium wp-image-117" /></p>
<p>Not that straightforward, actually. Apple includes the Hoefler Text font in Mac OS X - its a really nice and readable professional font. Here&#8217;s what I did:</p>
<p><span id="more-113"></span></p>
<p>(1) You need to obtain the font in the opentype format (otf). Be careful: for me, the TTF version didn&#8217;t work. The Postscript type 1 version worked great.<br />
(2) Use otftotfm -a to convert and install the files:<br />
<code><br />
otftotfm -a -e texnansx HoeflerText-Regular.otf -fkern -fliga LY1&#8211;HoeflerText-Regular<br />
</code><br />
This installs the regular form in the .texlive subdirectory of your home directory. Do this for all the font shapes you want to use. In the last step you need to create a .fd file:<br />
<code><br />
\DeclareFontFamily{LY1}{HoeflerText}{}\DeclareFontShape{LY1}{HoeflerText}{m}{n}%<br />
        { < -> LY1&#8211;HoeflerText-Regular }{}<br />
\DeclareFontShape{LY1}{HoeflerText}{m}{it}{ < -> LY1&#8211;HoeflerText-Italic }{}<br />
\DeclareFontShape{LY1}{HoeflerText}{m}{sl}{ < -> LY1&#8211;HoeflerText-Bold }{}<br />
\DeclareFontShape{LY1}{HoeflerText}{b}{n}{ < -> LY1&#8211;HoeflerText-Bold }{}\DeclareFontShape{LY1}{HoeflerText}{b}{it}%<br />
        { < -> LY1&#8211;HoeflerText-BoldItalic }{}<br />
</code><br />
Put this in ~/.texlive2008/texmf-var/tex/latex/HoeflerText/LY1HoeflerText.fd. Again, make sure that all font shapes you want to use are included.</p>
<p>In your Latex document, put<br />
<code><br />
\usepackage[LY1]{fontenc}<br />
\renewcommand{\rmdefault}{HoeflerText}<br />
</code><br />
to use the font.</p>
<p>The picture above was CCed on flickr by <a href="http://flickr.com/photos/liikennevalo/3022406574/">liikennevalo</a>, thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/11/23/installing-hoefler-text-in-latex/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Code Kata: Project Euler #7, Finding Primes</title>
		<link>http://gonium.net/md/2008/09/08/code-kata-project-euler-7-finding-primes/</link>
		<comments>http://gonium.net/md/2008/09/08/code-kata-project-euler-7-finding-primes/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 08:08:52 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[codekata]]></category>

		<category><![CDATA[erlang]]></category>

		<category><![CDATA[primes]]></category>

		<category><![CDATA[projecteuler]]></category>

		<guid isPermaLink="false">http://gonium.net/md/?p=100</guid>
		<description><![CDATA[
I resumed my code katas - this time, I&#8217;m using Erlang to solve the problem:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?



It seems to be clever to have a prime number generator for Project Euler [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://gonium.net/md/wp-content/uploads/2008/09/338443480_8127cdd845_o.jpg" alt="" title="Ulam_Spiral" width="500" height="333" class="alignnone size-full wp-image-101" /></p>
<p>I resumed my code katas - this time, I&#8217;m using Erlang to solve the problem:</p>
<blockquote><p>
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.<br />
What is the 10001st prime number?
</p>
</blockquote>
<p><span id="more-100"></span></p>
<p>It seems to be clever to have a prime number generator for Project Euler anyway. My implementation is based on the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Erathosthenes</a> and uses the <a href="http://mathworld.wolfram.com/PrimeNumberTheorem.html">Prime Number Theorem</a> for an estimate on the size of the sieve. The code is pretty easy:</p>
<pre class="vci_code">
<span style="color:#8080ff">%% Solves Project Euler task #7: </span>
<span style="color:#8080ff">%% &quot;By listing the first six prime numbers: 2, 3, 5, 7, 11, </span>
<span style="color:#8080ff">%% and 13, we can see that the 6th prime is 13.</span>
<span style="color:#8080ff">%% What is the 10001st prime number?&quot;</span>
<span style="color:#8080ff">%% Solution idea: Use the sieve of Erathosthenes.</span>
<span style="color:#8080ff">%% Copyleft Mathias Dalheimer, 09/08/2008.</span>

<span style="color:#00ff00">-module</span>(pe7)<span style="color:#ff40ff">.</span>
<span style="color:#00ff00">-export</span>([sieve<span style="color:#ffff00">/</span><span style="color:#ff6060">1</span>, nthprime<span style="color:#ffff00">/</span><span style="color:#ff6060">1</span>, info<span style="color:#ffff00">/</span><span style="color:#ff6060">0</span>])<span style="color:#ff40ff">.</span>

info() <span style="color:#ffff00">-&gt;</span>
  <span style="color:#00ffff">io</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">format</span>(<span style="color:#ff6060">&quot;Project Euler Problem #7 - use nthprime(10001).</span><span style="color:#ff40ff">~n</span><span style="color:#ff6060">&quot;</span>)<span style="color:#ff40ff">.</span>

nthprime(N) <span style="color:#ffff00">-&gt;</span>
  <span style="color:#8080ff">% First, estimate the upper bound for Erathosthenes sieve,</span>
  <span style="color:#8080ff">% then use it. See</span>
  <span style="color:#8080ff">%   <a href="http://mathworld.wolfram.com/PrimeNumberTheorem.html">http://mathworld.wolfram.com/PrimeNumberTheorem.html</a></span>
  <span style="color:#8080ff">% for more information on the estimate method.</span>
  Max <span style="color:#ffff00">=</span> <span style="color:#00ffff">round</span>(N<span style="color:#ffff00">*</span>(<span style="color:#00ffff">math</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">log</span>(N) <span style="color:#ffff00">+</span> <span style="color:#00ffff">math</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">log</span>(<span style="color:#00ffff">math</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">log</span>(N-1)))),
  <span style="color:#00ffff">io</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">format</span>(<span style="color:#ff6060">&quot;Estimated upper bound for sieve: </span><span style="color:#ff40ff">~p~n</span><span style="color:#ff6060">&quot;</span>, [Max]),
  nthprime(N, Max)<span style="color:#ff40ff">.</span>

nthprime(N, Max) <span style="color:#ffff00">-&gt;</span>
  T1 <span style="color:#ffff00">=</span> <span style="color:#00ffff">erlang</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">now</span>(),
  Primes <span style="color:#ffff00">=</span> sieve(Max),
  T2 <span style="color:#ffff00">=</span> <span style="color:#00ffff">erlang</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">now</span>(),
  <span style="color:#00ffff">io</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">format</span>(<span style="color:#ff6060">&quot;Runtime of Erathosthenes sieve: </span><span style="color:#ff40ff">~p</span><span style="color:#ff6060"> ms.</span><span style="color:#ff40ff">~n</span><span style="color:#ff6060">&quot;</span>,
    [(<span style="color:#ff40ff">timer</span><span style="color:#ff40ff">:</span>now_diff(T2, T1) <span style="color:#ffff00">/</span> 1000)]),
  <span style="color:#00ffff">lists</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">nth</span>(N, Primes)<span style="color:#ff40ff">.</span>

sieve(Max) <span style="color:#ffff00">-&gt;</span>
  Boundary <span style="color:#ffff00">=</span> <span style="color:#00ffff">round</span>(<span style="color:#00ffff">math</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">sqrt</span>(Max))<span style="color:#ff6060">+1</span>,
  erathosthenes(<span style="color:#00ffff">lists</span><span style="color:#ff40ff">:</span><span style="color:#00ffff">seq</span>(<span style="color:#ff6060">2</span>, Max), <span style="color:#ff6060">2</span>, Boundary)<span style="color:#ff40ff">.</span>

isMultipleOf(X, Base) <span style="color:#ffff00">-&gt;</span>
  <span style="color:#ffff00">if</span>
    X <span style="color:#ffff00">=</span><span style="color:#ff40ff">:</span><span style="color:#ffff00">=</span> Base <span style="color:#ffff00">-&gt;</span> <span style="color:#ffff00">true</span>;
    (X <span style="color:#ffff00">rem</span> Base <span style="color:#ffff00">=</span><span style="color:#ff40ff">:</span><span style="color:#ffff00">=</span> <span style="color:#ff6060">0</span>) <span style="color:#ffff00">-&gt;</span> <span style="color:#ffff00">false</span>;
    <span style="color:#ffff00">true</span> <span style="color:#ffff00">-&gt;</span> <span style="color:#ffff00">true</span>
  <span style="color:#ffff00">end</span><span style="color:#ff40ff">.</span>

erathosthenes(Numbers, Index, Boundary) <span style="color:#ffff00">when</span> Index <span style="color:#ffff00">=&lt;</span> Boundary <span style="color:#ffff00">-&gt;</span>
  PurgedNumbers <span style="color:#ffff00">=</span> [X || X <span style="color:#ffff00">&lt;-</span> Numbers, isMultipleOf(X, Index)],
  <span style="color:#8080ff">%io:format(&quot;DEBUG: \tNumbers = ~p,~n\tBoundary = ~p ~n&quot;, [PurgedNumbers, Boundary]),</span>
  <span style="color:#8080ff">%io:format(&quot;Boundary = ~p ~n&quot;, [Boundary]),</span>
  erathosthenes(PurgedNumbers, Index<span style="color:#ff6060">+1</span>, Boundary);
erathosthenes(Numbers, <span style="color:#ff40ff">_</span>, <span style="color:#ff40ff">_</span>) <span style="color:#ffff00">-&gt;</span>
  Numbers<span style="color:#ff40ff">.</span>
</pre>
<p class="vci_info">HTML code generated by <a href="http://www.zacharyfox.com/blog/free-tools/vim-color-improved">vim-color-improved v.0.4.0.</a><strong>Download this code:</strong> <a href="http://gonium.net/media//pe7.erl">pe7.erl</a></p>
<p>In the erathosthenes function, a list comprehension is used to purge all multiplies of the current Index value. My first attempt didn&#8217;t include the Index variable - I simply decreased the boundary. The disadvantage of this method is that it keeps the list of primes bigger over the runtime: Instead of removing the multiples of 2 at the very beginning, they get removed as the last multiples. The size of PurgedNumbers stays bigger, which leads to a runtime of 6.7 seconds. When I use the Index variable, the multiples of 2 get removed first which avoids copying them all the way. The runtime decreases to 1.2 seconds (on my Mac Mini).</p>
<p>Since all variables in Erlang are bound only once, I don&#8217;t know how to optimize this further. In C, I would use a bit array to further reduce the memory footprint. But: the Erlang code is much easier to read and write. I think Erlang is just not made for low memory bandwidth requirements :-)</p>
<p>The picture above is an representation of the <a href="http://en.wikipedia.org/wiki/Ulam_spiral">Ulam spiral</a>, CCed on flickr by <a href="http://flickr.com/photos/kusamakura/338443480/">no_typographic_man</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/09/08/code-kata-project-euler-7-finding-primes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>FreeRTOS for ATMega644</title>
		<link>http://gonium.net/md/2008/08/10/freertos_for_atmega644/</link>
		<comments>http://gonium.net/md/2008/08/10/freertos_for_atmega644/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 16:19:26 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[ATMega]]></category>

		<category><![CDATA[microcontroller]]></category>

		<category><![CDATA[port]]></category>

		<category><![CDATA[rtos]]></category>

		<guid isPermaLink="false">http://gonium.net/md/?p=89</guid>
		<description><![CDATA[
FreeRTOS is an open-source realtime operating system for microcontrollers. The ATMega644 of ATMEL provides 64KB of flash program memory in a DIY-friendly 40-pin PDIP package. Read on for how to combine both to my new software development platform.

FreeRTOS provides a nice RTOS for embedded systems and is readily available for various platforms. One timer of [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://gonium.net/md/wp-content/uploads/2008/08/1365045226_4e46522658.jpg" alt="six-legged chip bug" title="chip_bug" width="300" height="225" class="alignnone size-medium wp-image-90" /></p>
<p><a href="http://www.freertos.org/">FreeRTOS</a> is an open-source realtime operating system for microcontrollers. The <a href="http://www.atmel.com/dyn/products/product_card.asp?part_id=3694">ATMega644</a> of ATMEL provides 64KB of flash program memory in a DIY-friendly 40-pin PDIP package. Read on for how to combine both to my new software development platform.<br />
<span id="more-89"></span><br />
FreeRTOS provides a nice RTOS for embedded systems and is readily available for various platforms. One timer of the hardware is used to implement multitasking features. A library provides routines for creating tasks and synchronization. Unfortunately, FreeRTOS is currently only ported to the ATMega323 - so I created a basic port to the ATMega644 and stripped all unnecessary features.</p>
<p>Typically, the FreeRTOS demo shows how to implement various threads and let them access the hardware. While it is educating to read the code, it is too bloated to serve as a template for new developments. In addition, I prefer <a href="http://jump.to/fleury">Peter Fleury&#8217;s UART library</a> for serial outputs. So, I removed all threads and included the library. To make sure that two threads cannot write to the same UART at the same time, I introduced a mutex per UART to synchronize the output on a per-string basis. Please note that there is no Mutex to synchronize read access. The main program starts two tasks which print &#8220;foo&#8221; and &#8220;bar&#8221; to the serial line, respectively. I kept the task surveilance mechanism as implemented in the original FreeRTOS demo (this might become handy ;-))</p>
<p>Here is a peek at the main.c file:</p>
<pre class="vci_code">
<span style="color:#8080ff">/*</span><span style="color:#8080ff"> Based on FreeRTOS Demo main (AVR-GCC Port). </span><span style="color:#8080ff">*/</span>

<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&lt;stdlib.h&gt;</span>
<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&lt;string.h&gt;</span>
<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&lt;avr/eeprom.h&gt;</span>
<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&lt;avr/interrupt.h&gt;</span>
<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&lt;avr/pgmspace.h&gt;</span>

<span style="color:#8080ff">/*</span><span style="color:#8080ff"> Scheduler include files. </span><span style="color:#8080ff">*/</span>
<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&quot;FreeRTOS.h&quot;</span>
<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&quot;task.h&quot;</span>
<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&quot;croutine.h&quot;</span>

<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&quot;status.h&quot;</span>
<span style="color:#ff40ff">#include </span><span style="color:#ff6060">&quot;uart.h&quot;</span>

<span style="color:#8080ff">/*</span><span style="color:#8080ff"> Priority definitions for most of the tasks in the demo application.  Some</span>
<span style="color:#8080ff">tasks just use the idle priority. </span><span style="color:#8080ff">*/</span>
<span style="color:#ff40ff">#define mainCHECK_TASK_PRIORITY                 ( tskIDLE_PRIORITY + </span><span style="color:#ff6060">3</span><span style="color:#ff40ff"> )</span>

<span style="color:#8080ff">/*</span><span style="color:#8080ff"> Baud rate used by the serial port tasks. </span><span style="color:#8080ff">*/</span>
<span style="color:#ff40ff">#define UART_BAUD_RATE                  ( ( </span><span style="color:#00ff00">unsigned</span><span style="color:#ff40ff"> portLONG ) </span><span style="color:#ff6060">9600</span><span style="color:#ff40ff"> )</span>

<span style="color:#8080ff">/*</span><span style="color:#8080ff"> define CPU frequency in Mhz here if not defined in Makefile </span><span style="color:#8080ff">*/</span>
<span style="color:#ff40ff">#ifndef F_CPU</span>
<span style="color:#ff40ff">#define F_CPU </span><span style="color:#ff6060">16000000UL</span>
<span style="color:#ff40ff">#endif</span>

<span style="color:#8080ff">/*</span><span style="color:#8080ff"> LED that is toggled by the check task.  The check task periodically checks</span>
<span style="color:#8080ff">that all the other tasks are operating without error.  If no errors are found</span>
<span style="color:#8080ff">the LED is toggled.  If an error is found at any time the LED is never toggles</span>
<span style="color:#8080ff">again. </span><span style="color:#8080ff">*/</span>
<span style="color:#ff40ff">#define mainCHECK_TASK_LED                              ( </span><span style="color:#ff6060">7</span><span style="color:#ff40ff"> )</span>

<span style="color:#8080ff">/*</span><span style="color:#8080ff"> The period between executions of the check task. </span><span style="color:#8080ff">*/</span>
<span style="color:#ff40ff">#define mainCHECK_PERIOD                                ( ( portTickType ) </span><span style="color:#ff6060">3000</span><span style="color:#ff40ff"> / portTICK_RATE_MS  )</span>

<span style="color:#8080ff">/*</span>
<span style="color:#8080ff"> * Function prototypes, see below.</span>
<span style="color:#8080ff"> </span><span style="color:#8080ff">*/</span>
<span style="color:#00ff00">static</span> <span style="color:#00ff00">void</span> serialWriter( <span style="color:#00ff00">void</span> *pvParameters );
<span style="color:#00ff00">static</span> <span style="color:#00ff00">void</span> vErrorChecks( <span style="color:#00ff00">void</span> *pvParameters );
<span style="color:#00ff00">static</span> <span style="color:#00ff00">void</span> prvCheckOtherTasksAreStillRunning( <span style="color:#00ff00">void</span> );
<span style="color:#00ff00">void</span> vApplicationIdleHook( <span style="color:#00ff00">void</span> );

<span style="color:#8080ff">/*</span>
<span style="color:#8080ff"> * status variables.</span>
<span style="color:#8080ff"> </span><span style="color:#8080ff">*/</span>
<span style="color:#00ff00">static</span> portBASE_TYPE serialWriterStatus = pdTRUE;

portSHORT main( <span style="color:#00ff00">void</span> ) {
  <span style="color:#8080ff">/*</span><span style="color:#8080ff"> Setup the LED's for output. </span><span style="color:#8080ff">*/</span>
  statusInitialize();
  uart_init( UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU) );
  sei();

  <span style="color:#8080ff">/*</span><span style="color:#8080ff"> Create the tasks defined within this file. </span><span style="color:#8080ff">*/</span>
  xTaskCreate( vErrorChecks, ( <span style="color:#00ff00">signed</span> portCHAR * ) <span style="color:#ff6060">&quot;Check&quot;</span>, configMINIMAL_STACK_SIZE, <span style="color:#ff6060">NULL</span>, mainCHECK_TASK_PRIORITY, <span style="color:#ff6060">NULL</span> );
  xTaskCreate( serialWriter, ( <span style="color:#00ff00">signed</span> portCHAR * ) <span style="color:#ff6060">&quot;Foo&quot;</span>, configMINIMAL_STACK_SIZE, <span style="color:#ff6060">&quot;foo&quot;</span>, mainCHECK_TASK_PRIORITY, <span style="color:#ff6060">NULL</span> );
  xTaskCreate( serialWriter, ( <span style="color:#00ff00">signed</span> portCHAR * ) <span style="color:#ff6060">&quot;Bar&quot;</span>, configMINIMAL_STACK_SIZE, <span style="color:#ff6060">&quot;bar&quot;</span>, mainCHECK_TASK_PRIORITY, <span style="color:#ff6060">NULL</span> );
  uart_puts_P(<span style="color:#ff6060">&quot;</span><span style="color:#ff40ff">\r\n</span><span style="color:#ff6060">FreeRTOS template initialized.&quot;</span>);

  vTaskStartScheduler();
  <span style="color:#ffff00">return</span> <span style="color:#ff6060">0</span>;
}

<span style="color:#00ff00">static</span> <span style="color:#00ff00">void</span> vErrorChecks( <span style="color:#00ff00">void</span> *pvParameters ) {
  <span style="color:#8080ff">/*</span><span style="color:#8080ff"> The parameters are not used. </span><span style="color:#8080ff">*/</span>
  ( <span style="color:#00ff00">void</span> ) pvParameters;

  <span style="color:#8080ff">/*</span><span style="color:#8080ff"> Cycle for ever, delaying then checking all the other tasks are still</span>
<span style="color:#8080ff">     operating without error. </span><span style="color:#8080ff">*/</span>
  <span style="color:#ffff00">for</span>( ;; ) {
    vTaskDelay( mainCHECK_PERIOD );
    prvCheckOtherTasksAreStillRunning();
  }
}

<span style="color:#00ff00">static</span> <span style="color:#00ff00">void</span> serialWriter( <span style="color:#00ff00">void</span> *pvParameters ) {
  <span style="color:#00ff00">char</span>* message = pvParameters;
  <span style="color:#ffff00">for</span> (;;) {
        vTaskDelay((portTickType) <span style="color:#ff6060">100</span>/portTICK_RATE_MS);
        <span style="color:#8080ff">/*</span><span style="color:#8080ff"> Notify a single error. </span><span style="color:#8080ff">*/</span>
        <span style="color:#ffff00">if</span> (uart_puts_P(<span style="color:#ff6060">&quot;</span><span style="color:#ff40ff">\r\n</span><span style="color:#ff6060">&quot;</span>) != pdTRUE)
          serialWriterStatus = pdFALSE;
        <span style="color:#ffff00">if</span> (uart_puts(message) != pdTRUE)
          serialWriterStatus = pdFALSE;
  }
}

<span style="color:#00ff00">static</span> <span style="color:#00ff00">void</span> prvCheckOtherTasksAreStillRunning( <span style="color:#00ff00">void</span> ) {
  <span style="color:#00ff00">static</span> portBASE_TYPE xErrorHasOccurred = pdFALSE;
  <span style="color:#ffff00">if</span>( serialWriterStatus != pdTRUE ) {
    xErrorHasOccurred = pdTRUE;
  }

  <span style="color:#ffff00">if</span>( xErrorHasOccurred == pdFALSE ) {
    <span style="color:#8080ff">/*</span><span style="color:#8080ff"> Toggle the LED if everything is okay so we know if an error occurs even if not</span>
<span style="color:#8080ff">       using console IO. </span><span style="color:#8080ff">*/</span>
    statusToggleLED( mainCHECK_TASK_LED );
    uart_puts_P(<span style="color:#ff6060">&quot;</span><span style="color:#ff40ff">\r\n</span><span style="color:#ff6060">All tasks working.&quot;</span>);
  }
}

<span style="color:#00ff00">void</span> vApplicationIdleHook( <span style="color:#00ff00">void</span> ) {
  vCoRoutineSchedule();
}
</pre>
<p class="vci_info">HTML code generated by <a href="http://www.zacharyfox.com/blog/free-tools/vim-color-improved">vim-color-improved v.0.4.0.</a><strong>Download this code:</strong> <a href="http://gonium.net/media//freertos-atmega644-main.c">freertos-atmega644-main.c</a></p>
<p>You can get the whole package (GPL licensed) from the download page. Have fun! Kudos for the CC&#8217;ed chip bug picture go to <a href="http://flickr.com/photos/oskay/1365045226/">oskay</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/08/10/freertos_for_atmega644/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Generating random numbers from any distribution</title>
		<link>http://gonium.net/md/2008/07/29/generating-random-numbers-from-any-distribution/</link>
		<comments>http://gonium.net/md/2008/07/29/generating-random-numbers-from-any-distribution/#comments</comments>
		<pubDate>Tue, 29 Jul 2008 09:22:52 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[distribution]]></category>

		<category><![CDATA[gaussian]]></category>

		<category><![CDATA[random]]></category>

		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gonium.net/md/?p=85</guid>
		<description><![CDATA[
At work I needed to generate random numbers following a combination of two gaussian distributions - which gave me some headache until someone pointed me to using a Monte Carlo approach. Here&#8217;s how.

Typically, any programming language provides some way to generate uniformly distributed random numbers, typically in the interval [0,1]. A histogram of the values [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://gonium.net/md/wp-content/uploads/2008/07/381184220_4cfce0c86a.jpg" alt="" title="random dices"  class="alignnone size-medium wp-image-86" /></p>
<p>At work I needed to generate random numbers following a combination of two gaussian distributions - which gave me some headache until someone pointed me to using a Monte Carlo approach. Here&#8217;s how.</p>
<p><span id="more-85"></span></p>
<p>Typically, any programming language provides some way to generate uniformly distributed random numbers, typically in the interval [0,1]. A histogram of the values looks like this:</p>
<p><img src="http://gonium.net/md/wp-content/uploads/2008/07/uniform.png" alt="" title="uniform" class="alignnone size-medium wp-image-87" /></p>
<p>However, I needed random numbers following the joint distribution of two gaussian distributions. The histogram should look like this:</p>
<p><img src="http://gonium.net/md/wp-content/uploads/2008/07/doublegaussian.png" alt="" title="doublegaussian" class="alignnone size-medium wp-image-88" /></p>
<p>It turns out that it is rather simple to generate random numbers from an given probability density function (PDF) f(x). The only restriction is that there exists another density function g(x) such that c*g(x) majorizes the density function f(x):</p>
<p>c*g(x) &gt;= f(x) for all x.</p>
<p>The steps are rather simple - to generate a random variate x with density f(x):</p>
<ol>
<li>Generate x with PDF g(x)</li>
<li>Generate y uniform on [0, cg(x)]</li>
<li>If y &lt;= f(x), then output x and return - otherwise repeat from step 1.</li>
</ol>
<p>Please note that this approach is applicable to many PDFs, but it can be rather slow, depending on the &#8220;hit rate&#8221;. The algorithm is simple: You generate two uniform random numbers, x and y. Then, you check if y &lt; f(x) - if true, add x to your collection of random numbers. Otherwise, discard it. Repeat the steps until you have enough random numbers. This method is also called Rejection Sampling and was first described by John von Neumann. Other techniques include Inverse Transformation, Composition and Convolution.</p>
<p>I highly recommend reading Chapters 28 and 29 of Rai Jain&#8217;s &#8220;The Art of Computer Systems Performance Analysis&#8221; which outline techniques for generating random numbers of several distributions.</p>
<p>My ruby implementation consists of a MC wrapper and blocks compute the random variate. Currently, I can create gaussian distributions, exponential distributions and a combination of two gaussian distributions. The toolbox also contains a method to scale the range of the random numbers using a linear transformation approach.</p>
<pre class="vci_code">
<span style="color:#8080ff"># This file is part of the calana grid workload generator.</span>
<span style="color:#8080ff"># (c) 2008 Mathias Dalheimer, md@gonium.net</span>
<span style="color:#8080ff">#</span>
<span style="color:#8080ff"># The calana grid work$load generator (CGWG) is free software; you can </span>
<span style="color:#8080ff"># redistribute it and/or modify it under the terms of the GNU General Public </span>
<span style="color:#8080ff"># License as published by the Free Software Foundation; either version 2 of </span>
<span style="color:#8080ff"># the License, or any later version.</span>
<span style="color:#8080ff">#</span>
<span style="color:#8080ff"># CGWG is distributed in the hope that it will be useful,</span>
<span style="color:#8080ff"># but WITHOUT ANY WARRANTY; without even the implied warranty of</span>
<span style="color:#8080ff"># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the</span>
<span style="color:#8080ff"># GNU General Public License for more details.</span>
<span style="color:#8080ff">#</span>
<span style="color:#8080ff"># You should have received a copy of the GNU General Public License</span>
<span style="color:#8080ff"># along with CGWG; if not, write to the Free Software</span>
<span style="color:#8080ff"># Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA</span>
<span style="color:#8080ff"># Read the CGWG location from the environment, warn otherwise</span>
<span style="color:#ffff00">if</span> (<span style="color:#00ffff">ENV</span>[<span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">CGWG_HOME</span><span style="color:#ff40ff">&quot;</span>] == <span style="color:#ff6060">nil</span>)
  puts <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">WARNING: Environment does not define $CGWG_HOME!</span><span style="color:#ff40ff">&quot;</span>
<span style="color:#ffff00">else</span>
  libpath= <span style="color:#00ffff">File</span>.join(<span style="color:#00ffff">File</span>.expand_path(<span style="color:#00ffff">ENV</span>[<span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">CGWG_HOME</span><span style="color:#ff40ff">&quot;</span>]), <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">lib</span><span style="color:#ff40ff">&quot;</span>)
  <span style="color:#00ffff">$:</span>.unshift &lt;&lt; libpath
<span style="color:#ffff00">end</span>

<span style="color:#ff40ff">class </span><span style="color:#00ff00">Range</span>
  <span style="color:#ffff00">attr_accessor</span> <span style="color:#00ffff">:min</span>, <span style="color:#00ffff">:max</span>
  <span style="color:#ff40ff">def </span><span style="color:#00ffff">initialize</span>(min=<span style="color:#ff6060">0.0</span>, max=<span style="color:#ff6060">1.0</span>)
    <span style="color:#00ffff">@min</span>=min; <span style="color:#00ffff">@max</span>=max;
  <span style="color:#ff40ff">end</span>
  <span style="color:#ff40ff">def </span><span style="color:#00ffff">to_s</span>
    <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">[</span><span style="color:#ff40ff">#{@min}</span><span style="color:#ff6060">, </span><span style="color:#ff40ff">#{@max}</span><span style="color:#ff6060">]</span><span style="color:#ff40ff">&quot;</span>
  <span style="color:#ff40ff">end</span>
<span style="color:#ff40ff">end</span>

<span style="color:#ff40ff">class </span><span style="color:#00ff00">RejectionException</span> &lt; <span style="color:#00ffff">StandardError</span>
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># A simple function that dumps the given array of values to</span>
<span style="color:#8080ff"># a file in the global temp directory -&gt; this is for debugging</span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">dumpRTable</span>(values, filename)
  filename = <span style="color:#00ffff">File</span>.join(<span style="color:#00ffff">ENV</span>[<span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">HOME</span><span style="color:#ff40ff">&quot;</span>], <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">tmp</span><span style="color:#ff40ff">&quot;</span>, filename);
  puts <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">Dumping values to </span><span style="color:#ff40ff">#{filename}</span><span style="color:#ff40ff">&quot;</span>
  <span style="color:#00ffff">File</span>.open(filename, <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">w</span><span style="color:#ff40ff">&quot;</span>) {|<span style="color:#00ffff">file</span>|
    file.puts(<span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">index</span><span style="color:#ff40ff">\t</span><span style="color:#ff6060">value</span><span style="color:#ff40ff">&quot;</span>)
    values.each_index{|<span style="color:#00ffff">index</span>|
      file.puts(<span style="color:#ff40ff">&quot;</span><span style="color:#ff40ff">#{index}</span><span style="color:#ff40ff">\t</span><span style="color:#ff40ff">#{values[index]}</span><span style="color:#ff40ff">&quot;</span>)
    }
  }
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># Enhance Array: Allow it to shuffle its contents randomly.</span>
<span style="color:#ff40ff">class </span><span style="color:#00ff00">Array</span>
  <span style="color:#ff40ff">def </span><span style="color:#00ffff">shuffle</span>
    sort_by { rand }
  <span style="color:#ff40ff">end</span>

  <span style="color:#ff40ff">def </span><span style="color:#00ffff">shuffle!</span>
    <span style="color:#ff6060">self</span>.replace shuffle
  <span style="color:#ff40ff">end</span>
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># Implements the MC approach - takes a block that checks if x &lt; pdf(y).</span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">generateMCRandoms</span>(amount)
  <span style="color:#ffff00">if</span> <span style="color:#ffff00">not</span> block_given?
    <span style="color:#ffff00">raise</span> <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">No probability density function check given - aborting</span><span style="color:#ff40ff">&quot;</span>
  <span style="color:#ffff00">end</span>
  values = <span style="color:#00ffff">Array</span>.new
  <span style="color:#ffff00">while</span> values.size() &lt; amount
    u1=rand()
    u2=rand()
    <span style="color:#ffff00">begin</span>
      distvalue = <span style="color:#ffff00">yield</span>(u1, u2)
      values &lt;&lt; distvalue
    <span style="color:#ffff00">rescue</span> <span style="color:#00ffff">RejectionException</span>
      <span style="color:#8080ff"># do nothing here, just don't add distvalue</span>
    <span style="color:#ffff00">end</span>
  <span style="color:#ffff00">end</span>
  <span style="color:#ffff00">return</span> values
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># Used for generating randoms for the user preference setting. </span>
<span style="color:#8080ff"># uses the composition method to multiplex two gaussian distributions.</span>
<span style="color:#8080ff"># </span><span style="background-color: #ffff00"><span style="color:#808080">TODO</span></span><span style="color:#8080ff">: Eliminate outliers before merging and scaling - see Walsh test,</span>
<span style="color:#8080ff"># <a href="http://www.statistics4u.info/fundstat_germ/ee_walsh_outliertest.html">http://www.statistics4u.info/fundstat_germ/ee_walsh_outliertest.html</a></span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">generateDoubleGaussianRandoms</span>(amount)
  range=<span style="color:#00ffff">Range</span>.new(<span style="color:#ff6060">0</span>,<span style="color:#ff6060">1</span>)
  leftvalues=generateGaussianRandoms(amount/<span style="color:#ff6060">2</span>,mean=<span style="color:#ff6060">0.1</span>,sd=<span style="color:#ff6060">0.1</span>)
  rightvalues=generateGaussianRandoms(amount/<span style="color:#ff6060">2</span>,mean=<span style="color:#ff6060">0.9</span>,sd=<span style="color:#ff6060">0.1</span>)
  values= (leftvalues + rightvalues)
  <span style="color:#8080ff"># We need to shuffle the randoms - otherwise, the two arrays would </span>
  <span style="color:#8080ff"># maintain their structure, which is not desired.</span>
  values.shuffle!
  <span style="color:#ffff00">return</span> linearTransformation(values, range)
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># Use rejection method to filter uniform randoms such that they </span>
<span style="color:#8080ff"># fit the gaussian distribution. See Raj Jain, &quot;The Art of Computer</span>
<span style="color:#8080ff"># Systems Performance Analysis&quot;, p. 494.</span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">generateGaussianRandoms</span>(amount, mean=<span style="color:#ff6060">0.0</span>, sd=<span style="color:#ff6060">1.0</span>, range=<span style="color:#ff6060">nil</span>)
  rawvalues = generateMCRandoms(amount) {|<span style="color:#00ffff">u1, u2</span>|
    x = - <span style="color:#00ffff">Math</span>.log(u1)
    y = <span style="color:#00ffff">Math</span>.exp((-(x-<span style="color:#ff6060">1</span>)**<span style="color:#ff6060">2</span>)/<span style="color:#ff6060">2</span>)
    <span style="color:#ffff00">if</span> (u2 &gt; y)
      <span style="color:#ffff00">raise</span> <span style="color:#00ffff">RejectionException</span>, <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">Not acceptable random number.</span><span style="color:#ff40ff">&quot;</span>
    <span style="color:#ffff00">else</span>
      u3=rand()
      <span style="color:#ffff00">if</span> (u3&gt;<span style="color:#ff6060">0.5</span>)
        mean+sd*x
      <span style="color:#ffff00">else</span>
        mean-sd*x
      <span style="color:#ffff00">end</span>
    <span style="color:#ffff00">end</span>
  }
  <span style="color:#ffff00">if</span> range != <span style="color:#ff6060">nil</span>
    <span style="color:#ffff00">return</span> linearTransformation(rawvalues, range)
  <span style="color:#ffff00">else</span>
    <span style="color:#ffff00">return</span> rawvalues
  <span style="color:#ffff00">end</span>
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># Generate randoms from an exponential distribution using the rejection</span>
<span style="color:#8080ff"># method. Actually, the inverse method would be far more efficient.</span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">generateExponentialRandoms</span>(amount, varlambda=<span style="color:#ff6060">1</span>, range=<span style="color:#ff6060">nil</span>)
  rawvalues = generateMCRandoms(amount) {|<span style="color:#00ffff">x, y</span>|
    expvalue = pdf_exponential(x, varlambda)
    <span style="color:#ffff00">if</span> (y &gt; expvalue)
      <span style="color:#ffff00">raise</span> <span style="color:#00ffff">RejectionException</span>, <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">Not acceptable random number.</span><span style="color:#ff40ff">&quot;</span>
    <span style="color:#ffff00">else</span>
      x
    <span style="color:#ffff00">end</span>
  }
  <span style="color:#ffff00">if</span> range != <span style="color:#ff6060">nil</span>
    <span style="color:#ffff00">return</span> linearTransformation(rawvalues, range)
  <span style="color:#ffff00">else</span>
    <span style="color:#ffff00">return</span> rawvalues
  <span style="color:#ffff00">end</span>
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># Scales a set of raw values using linear transformation.</span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">linearTransformation</span>(rawvalues, range)
  values=<span style="color:#00ffff">Array</span>.new()
  rawmin=rawvalues.min()
  rawmax=rawvalues.max()
  rawvalues.each{|<span style="color:#00ffff">val</span>|
    values &lt;&lt; ((range.max - range.min)/(rawmax-rawmin))*(val-rawmin)+range.min
  }
  <span style="color:#ffff00">return</span> values
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># Calculates the value of the probability density function (PDF)</span>
<span style="color:#8080ff"># for the gaussian distribution for x with the given parameters.</span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">pdf_gaussian</span>(x, mean, sd)
  <span style="color:#ffff00">return</span> (<span style="color:#ff6060">1</span>/(sd*<span style="color:#00ffff">Math</span>.sqrt(<span style="color:#00ffff">Math</span>::<span style="color:#00ffff">PI</span>*<span style="color:#ff6060">2</span>)))*<span style="color:#00ffff">Math</span>.exp(-((x-mean)**<span style="color:#ff6060">2</span>/(<span style="color:#ff6060">2</span>*sd**<span style="color:#ff6060">2</span>)))
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># The PDF of the exponential distribution</span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">pdf_exponential</span>(x, varlambda)
  <span style="color:#ffff00">if</span> (x&lt;<span style="color:#ff6060">0</span>)
    <span style="color:#ffff00">return</span> <span style="color:#ff6060">0</span>
  <span style="color:#ffff00">else</span>
    <span style="color:#ffff00">return</span> varlambda*<span style="color:#00ffff">Math</span>.exp(-varlambda * x)
  <span style="color:#ffff00">end</span>
<span style="color:#ff40ff">end</span>

<span style="color:#8080ff"># Generate simple uniformly distributed random numbers.</span>
<span style="color:#ff40ff">def </span><span style="color:#00ffff">generateUniformRandoms</span>(amount)
  values=<span style="color:#00ffff">Array</span>.new
  amount.downto(<span style="color:#ff6060">0</span>) {|<span style="color:#00ffff">index</span>|
    values &lt;&lt; rand()
  }
  values
<span style="color:#ff40ff">end</span>

<span style="color:#ffff00">if</span> <span style="color:#ff6060">__FILE__</span> == <span style="color:#00ffff">$0</span>
  <span style="color:#00ffff">$verbose</span> = <span style="color:#ff6060">true</span>
  amount=<span style="color:#ff6060">10000</span>
  uniforms=generateUniformRandoms(amount);
  dumpRTable(uniforms, <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">uniform.txt</span><span style="color:#ff40ff">&quot;</span>);
  gaussians=generateGaussianRandoms(amount, mean=<span style="color:#ff6060">0.0</span>, sd=<span style="color:#ff6060">1</span>, range=<span style="color:#00ffff">Range</span>.new(<span style="color:#ff6060">0.0</span>, <span style="color:#ff6060">1.0</span>));
  dumpRTable(gaussians, <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">gaussians.txt</span><span style="color:#ff40ff">&quot;</span>);
  rawgaussians=generateGaussianRandoms(amount, mean=<span style="color:#ff6060">0.0</span>, sd=<span style="color:#ff6060">1</span>);
  dumpRTable(rawgaussians, <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">rawgaussians.txt</span><span style="color:#ff40ff">&quot;</span>);
  doublegaussians=generateDoubleGaussianRandoms(amount);
  dumpRTable(doublegaussians, <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">doublegaussians.txt</span><span style="color:#ff40ff">&quot;</span>);
  exponentials=generateExponentialRandoms(amount, varlambda=<span style="color:#ff6060">1</span>, range=<span style="color:#00ffff">Range</span>.new(<span style="color:#ff6060">0</span>,<span style="color:#ff6060">1000</span>));
  dumpRTable(exponentials, <span style="color:#ff40ff">&quot;</span><span style="color:#ff6060">exponentials.txt</span><span style="color:#ff40ff">&quot;</span>);
<span style="color:#ffff00">end</span>
</pre>
<p class="vci_info">HTML code generated by <a href="http://www.zacharyfox.com/blog/free-tools/vim-color-improved">vim-color-improved v.0.4.0.</a><strong>Download this code:</strong> <a href="http://gonium.net/media//statistics.rb">statistics.rb</a></p>
<p>The title picture was CCed by <a href="http://flickr.com/photos/mamabarns/381184220/">Saffana</a>, thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/07/29/generating-random-numbers-from-any-distribution/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Code Kata: Project Euler #4, Finding Palindromes</title>
		<link>http://gonium.net/md/2008/04/19/code-kata-project-euler-4-finding-palindromes/</link>
		<comments>http://gonium.net/md/2008/04/19/code-kata-project-euler-4-finding-palindromes/#comments</comments>
		<pubDate>Sat, 19 Apr 2008 17:57:51 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[kata]]></category>

		<category><![CDATA[palindrome]]></category>

		<category><![CDATA[projecteuler]]></category>

		<guid isPermaLink="false">http://gonium.net/md/?p=83</guid>
		<description><![CDATA[
This weekend, I solved problem 4 of Project Euler:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

I designed a routine that checks whether a given number is a [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://gonium.net/md/wp-content/uploads/2008/04/527512317_de786ff9c3.jpg" alt="" title="527512317_de786ff9c3" width="330" height="500" class="alignnone size-full wp-image-84" /></p>
<p>This weekend, I solved problem 4 of Project Euler:</p>
<blockquote><p>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.</p>
<p>Find the largest palindrome made from the product of two 3-digit numbers.
</p></blockquote>
<p>I designed a routine that checks whether a given number is a palindrome. This routine is then used inside two loops iterating from 999 downto 0. The first hit is the largest palindrome. The core functionality is here:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
bool Problem4::isPalindrome(long number) {
  bool retval = false;
  std::vector<long> digits;
  while (number > 0) {
    long lastdigit = number % 10;
    digits.push_back(lastdigit);
    number = number / 10;
  }
  reverse(digits.begin(), digits.end());
  std::vector</long><long>::iterator front = digits.begin();
  std::vector</long><long>::iterator back = &#8211;digits.end();
  retval = false;
  while (! (front >= back)) {
    if ((*front) == (*back)) {
      retval = true;
      // move iterators to the next digits
      front++;
      back&#8211;;
    } else {
      // cannot be a palindrome, back out
      retval = false;
      break;
    }
  }
  return retval;
}
</textarea>
<p>This implementation reverses the vector. By using the front and back operators in the other direction, this could be left out. But it serves its purpose for now. You can get the full sourcecode from the download page. Please note that the code in the tarball calculates *all* palindromes smaller than 1000000.</p>
<p>The picture was CCed on flickr by <a href="http://flickr.com/photos/tisseurdetoile/527512317/">TisseurDeToile -[mangerait bien un petit chat]-</a>.</long></p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/04/19/code-kata-project-euler-4-finding-palindromes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Vertrauen in Internetbanking?</title>
		<link>http://gonium.net/md/2008/04/19/vertrauen-in-internetbanking/</link>
		<comments>http://gonium.net/md/2008/04/19/vertrauen-in-internetbanking/#comments</comments>
		<pubDate>Sat, 19 Apr 2008 08:35:29 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[deutsch]]></category>

		<category><![CDATA[digital]]></category>

		<category><![CDATA[absturz]]></category>

		<category><![CDATA[bank]]></category>

		<category><![CDATA[security]]></category>

		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://gonium.net/md/?p=81</guid>
		<description><![CDATA[
Eigentlich mag ich ja Internetbanking. Zu normalen Banköffnungszeiten arbeite ich, und ich bin nicht an lokale Banken gebunden. Meine bisherigen Erfahrungen waren auch recht positiv - allerdings beschleichen mich leichte Zweifel, wenn ich mir die Fehlermeldungen der Pluscard GmbH angucke.
Früher hab ich meine Kreditkartenauszüge einfach via Papierpost bekommen, kein Problem. Seitdem ich jedoch eine neue [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://gonium.net/md/wp-content/uploads/2008/04/pluscard-fehler.jpg'><img src="http://gonium.net/md/wp-content/uploads/2008/04/pluscard-fehler.jpg" alt="Fehlermeldung der Pluscard GmbH beim Abrufen meiner Kreditkartenabrechnung" title="pluscard-fehler" width="300" height="213" class="alignnone size-medium wp-image-82" /></a></p>
<p>Eigentlich mag ich ja Internetbanking. Zu normalen Banköffnungszeiten arbeite ich, und ich bin nicht an lokale Banken gebunden. Meine bisherigen Erfahrungen waren auch recht positiv - allerdings beschleichen mich leichte Zweifel, wenn ich mir die Fehlermeldungen der Pluscard GmbH angucke.</p>
<p>Früher hab ich meine Kreditkartenauszüge einfach via Papierpost bekommen, kein Problem. Seitdem ich jedoch eine neue Kreditkarte habe, bekomme ich die nur noch am Kontoauszugsdrucker - oder für 55 ct. via Post. Da ich oft vergesse, am Kontoauszugsdrucker vorbeizuschauen, hab ich mich für den Onlineabruf bei der Pluscard GmbH freischalten lassen.</p>
<p>Ich hatte schon öfter Probleme, mich dort erfolgreich einzuloggen. Heute morgen bekomme ich jedoch obige lustige Fehlermeldung (auf das Bild klicken für eine größere Version). Abgesehen davon, daß es einfach schlechter Stil ist, seinen Kunden so eine Seite zu präsentieren, verwundert mich die Technik dahinter:</p>
<blockquote><p>
Die schreiben meine Logindaten unverschlüsselt in eine &#8220;Fehler&#8221;-Datenbank!
</p>
</blockquote>
<p>Meine Kreditkarten- und Paßwortdaten habe ich natürlich ausgegraut, aber die standen da im Klartext. Drumherum noch viele Informationen über den Linux-Rechner (Ich tippe auf SuSE Linux irgendwas). Und was bitte schön haben KDE und Gnome auf einem Webserver verloren? Ich selbst soll also beim Onlinebanking keine Paßwörter notieren, meine Kreditkartennummer nicht weitergeben etc. Aber wenn es um die Fehlersuche geht, dann darf der Admin mal eben schnell alle möglichen Daten einsehen. Hm, was passiert wohl, wenn es jemandem gelingt, die Datenbank zu klauen?</p>
<p>Das eine <a href="http://gonium.net/md/2007/02/25/packstation-unavailable/">Packstation mal ausfällt</a>, ist ärgerlich, aber ok. Beim Onlinebanking erwarte ich wesentlich mehr.</p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/04/19/vertrauen-in-internetbanking/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Code Kata: Project Euler #3 + CMake distributions</title>
		<link>http://gonium.net/md/2008/04/13/code-kata-project-euler-3-cmake-distributions/</link>
		<comments>http://gonium.net/md/2008/04/13/code-kata-project-euler-3-cmake-distributions/#comments</comments>
		<pubDate>Sun, 13 Apr 2008 17:26:31 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[cmake]]></category>

		<category><![CDATA[prime]]></category>

		<category><![CDATA[projecteuler]]></category>

		<guid isPermaLink="false">http://gonium.net/md/2008/04/13/code-kata-project-euler-3-cmake-distributions/</guid>
		<description><![CDATA[
This weekend, I tackled the Project Euler problem #3:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

Pretty straightforward: Just test and recurse.

The core of the implementation is here:

  std::set&#60;ull&#62; Problem3::_findFactor(ull number, ull startFactor ) {
  std::set&#60;ull&#62; retval;
  for( ull factor [...]]]></description>
			<content:encoded><![CDATA[<p><img src='http://gonium.net/md/wp-content/uploads/2008/04/prime11.jpg' alt='11 is a prime' /></p>
<p>This weekend, I tackled the Project Euler problem #3:</p>
<blockquote><p>
The prime factors of 13195 are 5, 7, 13 and 29.<br />
What is the largest prime factor of the number 600851475143 ?
</p></blockquote>
<p>Pretty straightforward: Just test and recurse.<br />
<span id="more-78"></span><br />
The core of the implementation is here:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
  std::set&lt;ull&gt; Problem3::_findFactor(ull number, ull startFactor ) {
  std::set&lt;ull&gt; retval;
  for( ull factor = startFactor; factor < = number; factor += 1) {
	if (number % factor == 0) {
	  retval.insert(factor);
	  std::set&lt;ull&gt; recursive = _findFactor(number / factor, factor);
	  retval.insert(recursive.begin(), recursive.end());
	  break;
	}
  }
  return retval; 
}
</textarea>
<p>Please note that &#8220;ull&#8221; is a typedef for unsigned long long. For increasing integers, I test whether it is a factor of the given number. If yes, add it to the set of result values and descent one level into the recursion.</p>
<p>In addition, I extended my CMake infrastructure: You can now roll distributions based on CPack. In my oppinion you should start having a distribution target as early as possible within your development cycle. This way, you&#8217;re always ready to ship/deploy your software, i.e. for beta testers. Ship early, ship often&#8230; And of course automatically. When I type &#8220;make release&#8221;, CMake builds the software in release mode (&#8221;-O3&#8243;) and rolls several distributions. This is the output:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
Run CPack packaging tool...
CPack: Create package using PackageMaker
CPack: Install projects
CPack: - Run preinstall target for: PROBLEM3
CPack: - Install project: PROBLEM3
CPack: Compress package
Building in backwards compatible mode
Preverifying PROBLEM3
  Preverifying PROBLEM3
  Checking bundle identifiers
  Checking package configuration
  Checking contents
  Loading contents
  Checking for ZeroLink
Building PROBLEM3
  Building PROBLEM3
  Creating shell
  Copying scripts
  Writing description
  Writing bundle versions
  Copying resources
  Creating Requirements
  Creating permission hierarchy
  Creating Bill-of-Materials file
  Archiving files
  Creating Info.plist
CPack: Finalize package
CPack: Package /Users/gonium/Projects/project-euler/trunk/problem3/build/PROBLEM3-0.2.0-Darwin.dmg generated.
CPack: Create package using STGZ
CPack: Install projects
CPack: - Run preinstall target for: PROBLEM3
CPack: - Install project: PROBLEM3
CPack: Compress package
CPack: Finalize package
CPack: Package /Users/gonium/Projects/project-euler/trunk/problem3/build/PROBLEM3-0.2.0-Darwin.sh generated.
CPack: Create package using TGZ
CPack: Install projects
CPack: - Run preinstall target for: PROBLEM3
CPack: - Install project: PROBLEM3
CPack: Compress package
CPack: Finalize package
CPack: Package /Users/gonium/Projects/project-euler/trunk/problem3/build/PROBLEM3-0.2.0-Darwin.tar.gz generated.
</textarea>
<p>As you can see, a DMG image, a self-extracting shell installer and a tar.gz are built. The DMG contains all metadata for a nice MacOS installer - for Windows, a NSIS-based installer would have been created. CPack reuses the dependency information from my CMakeLists.txt files, so I don&#8217;t have to maintain another place and avoid duplication.</p>
<p>You simply add CPack to your toplevel CMakeLists.txt:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
# add some files to the installation target
INSTALL(FILES README.txt COPYRIGHT.txt DESTINATION share/PROBLEM3/doc)

# CPACK packaging
INCLUDE(InstallRequiredSystemLibraries)
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Project Euler Problem 3")
SET(CPACK_PACKAGE_VENDOR "Mathias Dalheimer")
SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.txt")
SET(CPACK_RESOURCE_FILE_LICENSE"${CMAKE_CURRENT_SOURCE_DIR}/COPYRIGHT.txt")
SET(CPACK_PACKAGE_VERSION_MAJOR ${V_MAJOR})
SET(CPACK_PACKAGE_VERSION_MINOR ${V_MINOR})
SET(CPACK_PACKAGE_VERSION_PATCH ${V_PATCH})
SET(CPACK_PACKAGE_INSTALL_DIRECTORY "CMake ${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}")
SET(CPACK_PACKAGE_EXECUTABLES "pe-problem3" "Solves Project Euler problem 3")
INCLUDE(CPack)
</textarea>
<p>I choose to add the resulting binary in a subsequent CMakeLists.txt where the binary is compiled:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
INSTALL(PROGRAMS ${PROBLEM3_BINARY_DIR}/src/pe-problem3 DESTINATION bin)
</textarea>
<p>Pretty easy and maintainable :-) You can get the source package from the download page.</p>
<p>Picture taken by <a href="http://flickr.com/photos/mc5/2092038798/">8#X and CCed on flickr.</p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/04/13/code-kata-project-euler-3-cmake-distributions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>New Vim config voodoo</title>
		<link>http://gonium.net/md/2008/04/11/new-vim-config-voodoo/</link>
		<comments>http://gonium.net/md/2008/04/11/new-vim-config-voodoo/#comments</comments>
		<pubDate>Fri, 11 Apr 2008 07:50:51 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[config]]></category>

		<category><![CDATA[cpp]]></category>

		<category><![CDATA[snippetsEmu]]></category>

		<category><![CDATA[vim]]></category>

		<category><![CDATA[voodoo]]></category>

		<guid isPermaLink="false">http://gonium.net/md/2008/04/11/new-vim-config-voodoo/</guid>
		<description><![CDATA[
I just added some new features to my vim configuration - check out these extensions:

snippetsEmu - simulates the snippets engine of Textmate. Simple configuration, high productivity impact.
Mark&#8217;s CPP vim templates to automatically create file skeletons for C++.

So, go and install some voodoo. Yum. Picture CC&#8217;ed by chaceofspades on flickr, thanks!
]]></description>
			<content:encoded><![CDATA[<p><img src='http://gonium.net/md/wp-content/uploads/2008/04/voodoo.jpg' alt='Voodoo' /></p>
<p>I just added some new features to my vim configuration - check out these extensions:</p>
<ul>
<li><a href="http://www.vim.org/scripts/script.php?script_id=13187">snippetsEmu</a> - simulates the snippets engine of Textmate. Simple configuration, high productivity impact.</li>
<li><a href="http://mark.jerde.org:13780/v1/comp/vim/#templates">Mark&#8217;s CPP vim templates</a> to automatically create file skeletons for C++.</li>
</ul>
<p>So, go and install some voodoo. Yum. Picture CC&#8217;ed by <a href="http://flickr.com/photos/chaceofspades/603841758/">chaceofspades</a> on flickr, thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/04/11/new-vim-config-voodoo/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Code Kata: Project Euler #2 with CMake</title>
		<link>http://gonium.net/md/2008/04/06/code-kata-project-euler-2-with-cmake/</link>
		<comments>http://gonium.net/md/2008/04/06/code-kata-project-euler-2-with-cmake/#comments</comments>
		<pubDate>Sun, 06 Apr 2008 10:41:35 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[autohell]]></category>

		<category><![CDATA[autotools]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[cmake]]></category>

		<category><![CDATA[kata]]></category>

		<category><![CDATA[projecteuler]]></category>

		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://gonium.net/md/2008/04/06/code-kata-project-euler-2-with-cmake/</guid>
		<description><![CDATA[
Recently, I started to use the autotools for building a project. But I am really unhappy with it - although a lot of special cases can be handled by the toolchain, it is extremely complex to use and prone to user errors. Auto-Hell, I guess&#8230; So, this code kata is dedicated to the alternative CMake [...]]]></description>
			<content:encoded><![CDATA[<p><img src='http://gonium.net/md/wp-content/uploads/2008/04/heavenorhell.jpg' alt='heaven or hell' /></p>
<p>Recently, I started to use the autotools for building a project. But I am really unhappy with it - although a lot of special cases can be handled by the toolchain, it is extremely complex to use and prone to user errors. Auto-Hell, I guess&#8230; So, this code kata is dedicated to the alternative <a href="http://cmake.org/HTML/index.html">CMake package</a>. I have written a simple C++ program to solve <a href="http://projecteuler.net/index.php?section=problems">problem #2</a> of Project Euler. </p>
<p><span id="more-72"></span></p>
<p>The autotools toolchain attempts to solve two problems:</p>
<ul>
<li>Configuration: On the compile system, where do libraries etc live?</li>
<li>Build: How is the software built?</li>
</ul>
<p>The configuration step is the famous &#8220;./configure&#8221; everyone comes across when installing software on unix systems. The autotools employ a mix of SH, Commandline-Magic, M4 and fairy dust to handle this. It generates Makefiles so that one can use make to build the software. Additional make targets such as make dist or make install help during deployment of the software.</p>
<p>The problem lies in the complexity of the toolchain: in the mixture of tools that build upon other tools, M4 macros and shell scripts, it is extremely difficult to find errors. If your buildsystem is as complex as the software you&#8217;re developing, something is wrong. In addition, the autotools are not really portable to other systems such as windows, at least not straightforward.</p>
<p>For these reasons the KDE project moved away from the autotools. They evaluated many different buildsystems and choose CMake. I played a little bit with it and I am quite happy. Of course, one needs to asses such a system in a bigger scenario in order to judge it, but at a first glance it really does the trick.</p>
<p>There are plenty of articles around - to get you started I suggest <a href="http://clubjuggler.livejournal.com/138364.html">Tanner Lovelace&#8217;s introduction</a>. In addition, the following resources are helpful:</p>
<ul>
<li><a href="http://www.linux-magazin.de/heft_abo/ausgaben/2007/02/mal_ausspannen">Mal ausspannen</a> (German, Linux-Magazin 02/2007)</li>
<li><a href="http://www.linuxjournal.com/article/6700">Cross-Platform Software Development Using CMake</a> (Linux Magazine)</li>
<li>The KDE subversion provides also a nice collection of <a href="http://websvn.kde.org/trunk/KDE/kdelibs/cmake/modules/">CMake scripts</a> which might give you some ideas.</li>
<li>The <a href="http://cmake.org/HTML/CMake-2.4.html">CMake manpage</a>, highly readable reference.
</li>
</ul>
<p>But now, on to building the software. My project directory has the following structure:<br />
<code><br />
.<br />
|&#8211; CMakeLists.txt<br />
|&#8211; Makefile<br />
|&#8211; Modules/<br />
|   `&#8211; FindLog4Cxx.cmake<br />
|&#8211; common/<br />
|   |&#8211; CMakeLists.txt<br />
|   |&#8211; common.h<br />
|   `&#8211; config.h.in<br />
|&#8211; problem2/<br />
|   |&#8211; CMakeLists.txt<br />
|   |&#8211; problem2.cpp<br />
|   `&#8211; problem2.hpp<br />
|&#8211; src/<br />
|   |&#8211; CMakeLists.txt<br />
|   `&#8211; main.cpp<br />
`&#8211; timer/<br />
    |&#8211; CMakeLists.txt<br />
    |&#8211; clock.cpp<br />
    `&#8211; clock.hpp<br />
</code></p>
<p>In order to keep things interesting I moved the code for solving the Project Euler task to the problem2 library. There&#8217;s a common library that defines project-wide settings. In timer, there&#8217;s a little routine for measuring execution times. The main routine lives in the src directory. </p>
<p>The CMakeList.txt files define the tasks to be done by CMake - this can be seen as the equivalent to the Makefile.am files. But you can define much more stuff in there. Here&#8217;s the top-level CMakeList.txt file:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
# Define project name and version numbers.
project (PROBLEM2)
set(V_MAJOR 0)
set(V_MINOR 1)
set(V_PATCH 1)

# add a path where some libraries might be stored
set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} /opt/local/include)
set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} /opt/local/lib)

# look for the external log4cxx library
set(LOG4CXX_FIND_REQUIRED true)
include(modules/FindLog4Cxx.cmake)

OPTION(ENABLE_LOGGING
  &#8220;Build the project with logging enabled&#8221;
  ON)
if(ENABLE_LOGGING)
  message(STATUS &#8220;Building with logging enabled.&#8221;)
endif(ENABLE_LOGGING)

# Make sure all subdirectories include correctly
include_directories(${CMAKE_CURRENT_BINARY_DIR})

# process the subdirectories in the right order.
add_subdirectory (common)
add_subdirectory (problem2)
add_subdirectory (timer)
add_subdirectory (src)
</textarea>
<p>I wanted to create a template which can be used as a staring point for later projects. I tend to use the Apache Log4CXX library for producing log messages. In order to discover the include and library directories, I created a CMake module - the equivalent of an Autotools M4 macro. CMake comes with lots of example modules for detecting libraries. But it is also easy to write your own modules. In contrast to the Autotools, all modules are specified in CMake&#8217;s own language.</p>
<p>Typically, you want to be able to deactivate all logging during the build process, e.g. prior to shipping the release version. You can define Options which can be set with various GUI tools. On Unix platforms, a curses-based GUI allows you to select your options. In this example, the ENABLE_LOGGING variable gets processed by the CMakeList.txt in the common directory:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
set(lib_src config.h common.h)

# create autotools-like config.h file from template. config.h will be
# generated in the build directory - add a global include so that we can
# find the config.h. In addition, copy the header-only common.h file to
# the build tree.
configure_file(config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h)
configure_file(common.h
  ${CMAKE_CURRENT_BINARY_DIR}/common.h COPYONLY)
</textarea>
<p>This generates a config.h file and copies it to the right location in the build directory. The config.h.in file defines some variables that will be replaced based on the values determined by CMake during the build step. Altogether, I like CMake. It is as powerful as the Autotools but without the quirks of the latter. You can download the example from the download page. There are other tools in the CMake package, namely CTest for testing software - but I&#8217;ll save this for another sunday ;-)</p>
<p>Finally, the Project Euler task is to solve the following problem:</p>
<blockquote><p>
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p>
<p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, &#8230;</p>
<p>Find the sum of all the even-valued terms in the sequence which do not exceed four million.
</p></blockquote>
<p>The code to solve this problem is pretty easy:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
unsigned long long sum, tmp = 1;
current = 2;
previous = 1;
while (current < _max) {
  if (current % 2 == 0)
    sum += current;
  tmp=current;
  current = current + previous;
  previous = tmp;
}
</textarea>
<p>The heaven or hell picture was CC&#8217;ed by <a href="http://flickr.com/photos/lin/24660690/">karmablue.</p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/04/06/code-kata-project-euler-2-with-cmake/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Code Kata: Project Euler #1</title>
		<link>http://gonium.net/md/2008/03/30/code-kata-project-euler-1/</link>
		<comments>http://gonium.net/md/2008/03/30/code-kata-project-euler-1/#comments</comments>
		<pubDate>Sun, 30 Mar 2008 18:13:39 +0000</pubDate>
		<dc:creator>md</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[nerdism]]></category>

		<category><![CDATA[c++]]></category>

		<category><![CDATA[learning]]></category>

		<category><![CDATA[performance]]></category>

		<category><![CDATA[projecteuler]]></category>

		<guid isPermaLink="false">http://gonium.net/md/2008/03/30/code-kata-project-euler-1/</guid>
		<description><![CDATA[Following the example of doing code katas, I spend my sunday morning thinking about integer performance in C++. Project Euler provides a nice collection of mathematical problems. As it turns out, some of my assumptions on C++ were totally wrong :-)

The problem to solve is the following:

If we list all the natural numbers below 10 [...]]]></description>
			<content:encoded><![CDATA[<p>Following the example of doing <a href="http://codekata.pragprog.com/2007/01/code_kata_backg.html">code katas</a>, I spend my sunday morning thinking about integer performance in C++. <a href="http://projecteuler.net/">Project Euler</a> provides a nice collection of mathematical problems. As it turns out, some of my assumptions on C++ were totally wrong :-)</p>
<p><span id="more-69"></span></p>
<p>The problem to solve is the following:</p>
<blockquote><p>
If we list all the natural numbers below 10 that are multiples of 3<br />
or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.  Find<br />
the sum of all the multiples of 3 or 5 below 1000.
</p></blockquote>
<p>Quite easy. A straightforward, naive implementation uses the modulo operator to filter the integers up to the maximum:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
unsigned long method1(const unsigned long max) {
  unsigned long sum=0;
  for (unsigned long i=0; i<max ; i++) {
	if ((i % 3) == 0 || ((i % 5) == 0))
	  sum += i;
  }
  return sum;
}
</textarea>
<p>On my Mac Mini, this method runs in 0.00947200 seconds for max=1000000.</p>
<p>I always thought of modulo being an expensive operation - this is probably the revenge for my scripting language preference. In order to avoid the modulo, I insert the multiples of 3 and 5 into a std::set and iterate over it afterwards:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
unsigned long method2(const unsigned long max) {
  unsigned long sum=0;
  std::set<unsigned long> torrent;
  for (unsigned long i=0; i</max><max ; i=i+3) {
	torrent.insert(i);
  }
  for (unsigned long i=0; i<max; i=i+5) {
	torrent.insert(i);
  }
  std::set<unsigned long>::iterator it;
  for (it=torrent.begin(); it != torrent.end(); it++) {
	sum += (*it);
  }
  return sum;
}
</textarea>
<p>Turns out this code is way slower than the first method: 0.34318700 seconds, more than two orders of magnitudes. Thinking of it, it is easy to see why: while the first method can completely run within the CPU, the second code suffers from accessing the main memory. I didn&#8217;t assess the overhead imposed by the std::set (no working gprof around). As it turns out, the C++ modulo operator uses the assembler div operation - so the compiler can optimize the code, keep all variables in registers, and use a fast operation.</p>
<p>However, the above code is not quite nice as it allows integer overflows for the sum variable. The <a href="http://gmplib.org/">GNU MP Bignum Library (GMP)</a> provides big integers. Method 3 uses them for the sum variable:</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
mpz_class method3(const unsigned long max) {
  mpz_class sum(0);
  for (unsigned long i=0; i</max><max ; i++) {
	if ((i % 3) == 0 || ((i % 5) == 0))
	  sum += i;
  }
  return sum;
}
</textarea>
<p>This method takes 0.018685 seconds - almost twice as long as method one. If i and max are of type mpz_class as well, the runtime increases to 0.581064 seconds. It looks like the compiler is no longer able to map the operations directly on the CPU.</p>
<p>Just out of curiosity, I changed the variable types of method 1 again to be unsigned long long (64bit-integers):</p>
<textarea name="code" class="c++:showcolumns:nogutter" cols="45" rows="10">
unsigned long long method5(const unsigned long long max) {
  unsigned long long sum=0;
  for (unsigned long long i=0; i<max; i++) {
	if ((i % 3) == 0 || ((i % 5) == 0))
	  sum += i;
  }
  return sum;
}
</textarea>
<p>This implementation is the fastest of all: 0.000905 seconds. Probably gcc maps the unsigned long long operations directly on SSE3 assembly instructions.</p>
<p>As a technical note, I used gcc version 4.0.1 (Apple Inc. build 5465) with -O3, the GMP library as supported by the macports. The output of my test program looks like this:<br />
<code><br />
Project Euler - Problem 1<br />
Method 1: 1404932684 -> 0.00952700 s.<br />
Method 2: 1404932684 -> 0.34736500 s.<br />
Method 3: 1404932684 -> 0.01851300 s.<br />
Method 4: 1404932684 -> 0.57744300 s.<br />
Method 5: 1404932684 -> 0.00094000 s.<br />
Creating comparison of methods 4 and 5<br />
100	2318(0.00006400)	2318(0.00001400)<br />
10000	23331668(0.00579500)	23331668(0.00043900)<br />
1000000	233333166668(0.57718100)	233333166668(0.05124100)<br />
100000000	2333333316666668(57.69583200)	2333333316666668(5.84172500)</p>
<p>You can download the code from the download page.</max></p>
]]></content:encoded>
			<wfw:commentRss>http://gonium.net/md/2008/03/30/code-kata-project-euler-1/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
