<?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>Algorithm.co.il &#187; Math</title>
	<atom:link href="http://www.algorithm.co.il/blogs/category/math/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.algorithm.co.il/blogs</link>
	<description>Algorithms, for the heck of it</description>
	<lastBuildDate>Tue, 21 Jun 2011 20:37:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>10 Awesome Theorems &amp; Results</title>
		<link>http://www.algorithm.co.il/blogs/computer-science/cryptography/10-awesome-theorems-results/</link>
		<comments>http://www.algorithm.co.il/blogs/computer-science/cryptography/10-awesome-theorems-results/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 00:00:39 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Theorem]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=647</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/computer-science/cryptography/10-awesome-theorems-results/' addthis:title='10 Awesome Theorems &#038; Results'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>When I look back at various mathematical courses I took, most have at least one theorem that I really liked. Usually I like it because the proof has a surprising trick, sometimes it&#8217;s because of the unexpected conclusion, or maybe &#8230; <a href="http://www.algorithm.co.il/blogs/computer-science/cryptography/10-awesome-theorems-results/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/computer-science/cryptography/10-awesome-theorems-results/' addthis:title='10 Awesome Theorems &#038; Results' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>When I look back at various mathematical courses I took, most have at least one theorem that I really liked. Usually I like it because the proof has a surprising trick, sometimes it&#8217;s because of the unexpected conclusion, or maybe the unintuitive feel to it. In other cases it&#8217;s just the elegance of the proof, or the result itself.<br />
Without further ado, here&#8217;s a selection of my favorite theorems, in no particular order:</p>
<p>1. Linear Algebra: the <a href="http://en.wikipedia.org/wiki/Cayley%E2%80%93Hamilton_theorem">Cayley Hamilton theorem</a>. When I first grokked the fact that you can substitute matrices for the variables in polynomials, I was awestruck. Then I learned that you can define e<sup>A</sup> by using a Taylor series, but the fun doesn&#8217;t stop there. Using the Eigenvalues you can greatly simplify the calculation, and it all &#8220;works out the same&#8221; (i.e., if A=P<sup>-1</sup>DP and D is diagonal, then p(A) = P<sup>-1</sup>p(D)P. This works also for Jordan forms). Also, since you can show that complex numbers are isomorphic to the 2&#215;2 matrices of the form [[a, b], [-b, a]], and that the calculations were exactly the same &#8211; well, everything &#8220;fell into place for me&#8221;. At the time it seemed to be one of the joys of Mathematics.</p>
<p>2. Calculus: the <a href="http://en.wikipedia.org/wiki/Bolzano%E2%80%93Weierstrass_theorem">Bolzano-Weierstrass Theorem</a>. One of the first non trivial results you learn in calculus, I originally learned the version that says: &#8220;Every bounded infinite set has a limit point&#8221;, and its proof was a bit more elegant in my eyes than the proof of the Wikipedia version. I liked it so much that one time when I was in boot camp in the service, I worked it out again just to keep my mind working. Good times.</p>
<p>3. Probability: The elegant result of <a href="http://en.wikipedia.org/wiki/Law_of_total_variance">V(x) = E(V(x|y)) + V(E(x|y))</a>. Just the sight of it makes one sigh with contentedness, and the result itself is very nice.</p>
<p>4. Calculus, again: <a href="http://en.wikipedia.org/wiki/Stokes%27_theorem">Stokes&#8217; theorem</a> and its friends. Very useful and non intuitive, in layman&#8217;s terms it says that you can reason about what happens in an area just by knowing about its perimeter.</p>
<p>5. Numerical Analysis: <a href="http://en.wikipedia.org/wiki/Richardson_extrapolation">Richardson Extrapolation</a>: one of the most elegant forms of bootstrapping, you start with a simple approximation method as a building block, and at the end you get a very strong high-quality approximation.</p>
<p>6. Computability: <a href="http://en.wikipedia.org/wiki/Smn_theorem">The Parameter theorem</a>. Especially elegant, it basically gives the mathematical definition of the &#8220;bind&#8221; function for function parameters. In simple terms it uses the source code of a function f(x, y), to find the source code of a function g(y) such that g(y) = f(a, y) for some a. The nice thing about it is that it works only on source code, without calling the function themselves.<br />
This theorem had the added bonus that once I grokked it, the test in computability was very, very easy :)</p>
<p>7. Functional analysis: here it&#8217;s a relatively minor result that I ended up remembering distinctly: Given z<sub>1</sub>.. z<sub>n</sub> which are linearly independent in E, show that there exists a d such that for each w<sub>1</sub>&#8230;w<sub>n</sub> that follow ||w<sub>i</sub> &#8211; z<sub>i</sub>|| &lt; d for each i, are also linearly independent. The footnote says that such a finite, linearly independent group is called stable. When visualizing I think of it this way: given a such a group, kick it. As long as you don&#8217;t kick it too strongly &#8211; it will stay linearly independent. Now that&#8217;s stable.</p>
<p>8.  Mathematical Logic: <a href="http://en.wikipedia.org/wiki/Compactness_theorem">The Compactness theorem</a>: &#8220;a set of first-order sentences has a model if and only if every finite subset of it has a model&#8221;. One direction is almost trivial, but the other is deep. When studying for the test in this course, I remember being stuck for days on an exercise that required the use of this theorem. Once I fully understood the method of its use, it became a favorite.<br />
(By the way, the exercise was the following: Let G a countable group of first order statements, and p a first order statement. Show that if p is true in every countable model of G, than G |= p.)</p>
<p>9. Cryptography: I&#8217;ve learned a bit of cryptography on my own before taking the cryptography course. When I did though, two methods were especially memorable: The first was the <a href="http://en.wikipedia.org/wiki/Meet-in-the-middle_attack">&#8220;Meet in the Middle&#8221; attack</a>. Not to be confused with &#8220;Man in the Middle&#8221;, this method allows one to attack symmetric ciphers constructed by repeatedly applying a simpler cipher. This known plaintext attack got its name from its method of operation: the attacker calculates all possible decryptions the ciphertext and stores them in a lookup table. Then, he calculates all encryptions of the plaintext and looks them up in that lookup table. Once a result is found &#8211; the combination of the encryption and the decryption keys used is the final key of the composed cipher.</p>
<p>10. The second cryptography result that I liked was <a href="http://en.wikipedia.org/wiki/Secret_sharing">secret sharing</a>. Trivial secret sharing is so simple, and yet effective, that when I first learned it I thought: &#8220;how come I didn&#8217;t think of this before?&#8221;.</p>
<p>There are obviously many more elegant theorems, some of which I&#8217;ve learned in my studies. I sure hope to learn a few more. Still, these are special. As a highschool math teacher once told us about the Pythagorean theorem: &#8220;I want you to remember the proof even if I wake you in the middle of the night&#8221;. The theorems in this short list come close to that ideal.</p>
<p>Now I wonder &#8211; what are your favorite theorems?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/computer-science/cryptography/10-awesome-theorems-results/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Visualizing Data Using the Hilbert Curve</title>
		<link>http://www.algorithm.co.il/blogs/math/visualizing-data-using-the-hilbert-curve/</link>
		<comments>http://www.algorithm.co.il/blogs/math/visualizing-data-using-the-hilbert-curve/#comments</comments>
		<pubDate>Sat, 17 Apr 2010 06:57:30 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[hilbert curve]]></category>
		<category><![CDATA[PIL]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=525</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/visualizing-data-using-the-hilbert-curve/' addthis:title='Visualizing Data Using the Hilbert Curve'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>Some time ago, a coworker asked me to help him visualize some data. He had a very long series (many millions) of data points, and he thought that plotting a pixel for each one would visualize it well, so he &#8230; <a href="http://www.algorithm.co.il/blogs/math/visualizing-data-using-the-hilbert-curve/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/visualizing-data-using-the-hilbert-curve/' addthis:title='Visualizing Data Using the Hilbert Curve' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>Some time ago, a coworker asked me to help him visualize some data. He had a very long series (many millions) of data points, and he thought that plotting a pixel for each one would visualize it well, so he asked for my help.<br />
I installed Python &#038; PIL on his machine, and not too long after, he had the image plotted. The script looked something like:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">data_points = get_data_points<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
n =  <span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span>data_points<span style="color: black;">&#41;</span><span style="color: #66cc66;">**</span><span style="color: #ff4500;">0.5</span><span style="color: black;">&#41;</span> + <span style="color: #ff4500;">0.5</span><span style="color: black;">&#41;</span>
&nbsp;
image = Image<span style="color: black;">&#40;</span><span style="color: #483d8b;">'1'</span>, <span style="color: black;">&#40;</span>n, n<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> idx, pt <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">enumerate</span><span style="color: black;">&#40;</span>data_points<span style="color: black;">&#41;</span>:
	image.<span style="color: black;">putpixel</span><span style="color: black;">&#40;</span>pt, <span style="color: black;">&#40;</span>idx/n, idx<span style="color: #66cc66;">%</span>n<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
image.<span style="color: black;">save</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'bla.png'</span>, <span style="color: #483d8b;">'png'</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Easy enough to do. Well, easy enough if you have enough memory to handle very large data sets. Luckily enough, we had just enough memory for this script &#038; data series, and we were happy. The image was generated, and everything worked fine.</p>
<p>Still, we wanted to improve on that. One problem with this visualization is that two horizontally adjacent pixels don’t have anything to do with each other. Remembering xkcd’s &#8220;<a href="http://xkcd.com/195/">Map of the Internet</a>&#8220;, I decided to use the <a href="http://en.wikipedia.org/wiki/Hilbert_curve">Hilbert Curve</a>. I started with wikipedia&#8217;s version of the code for the Python turtle and changed it to generate a string of instructions of where to put pixels. On the way I improved the time complexity by changing it to have only two recursion calls instead of four. (It can probably be taken down to one by the way, I leave that as a challenge to the reader :)</p>
<p>Unfortunately, at this point we didn’t have enough memory to hold all of those instructions, so I changed it into a generator. Now it was too slow. I cached the lower levels of the recursion, and now it worked in reasonable time (about 3-5 minutes), with reasonable memory requirements (no OutOfMemory exceptions). Of course, I&#8217;m skipping a bit of exceptions and debugging along the way. Still, it was relatively straightforward.</p>
<p>Writing the generator wasn&#8217;t enough &#8211; there were still pixels to draw! It took a few more minutes to write a simple &#8220;turtle&#8221;, that walks the generated hilbert curve.<br />
Now, we were ready:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">hilbert = Hilbert<span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">math</span>.<span style="color: black;">log</span><span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span>data_points<span style="color: black;">&#41;</span>, <span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span> + <span style="color: #ff4500;">0.5</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> pt <span style="color: #ff7700;font-weight:bold;">in</span> data_points:
    x,y = hilbert.<span style="color: black;">next</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    image.<span style="color: black;">putpixel</span><span style="color: black;">&#40;</span>pt, <span style="color: black;">&#40;</span>x,y<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>A few minutes later, the image was generated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/math/visualizing-data-using-the-hilbert-curve/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fast Peak Autocorrelation</title>
		<link>http://www.algorithm.co.il/blogs/math/fast-peak-autocorrelation/</link>
		<comments>http://www.algorithm.co.il/blogs/math/fast-peak-autocorrelation/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 12:58:55 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Utility Functions]]></category>
		<category><![CDATA[autocorellation]]></category>
		<category><![CDATA[automatic guitar improviser]]></category>
		<category><![CDATA[geekcon]]></category>
		<category><![CDATA[pyimprov]]></category>
		<category><![CDATA[signal processing]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=413</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/fast-peak-autocorrelation/' addthis:title='Fast Peak Autocorrelation'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>So, I was at geekcon. It was a blast. There were many interesting projects, and I didn&#8217;t get to play with them all. I did get to work a bit on the Lunar Lander from last year, and this year &#8230; <a href="http://www.algorithm.co.il/blogs/math/fast-peak-autocorrelation/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/fast-peak-autocorrelation/' addthis:title='Fast Peak Autocorrelation' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>So, I was at <a href="http://geekcon.org/">geekcon</a>. It was a blast.<br />
<img src="http://www.algorithm.co.il/sitecode/scaled_lunar_lander.jpg" alt="The lunar lander" style="border: 1px solid black; float: right; margin-left: 10px;"/><br />
There were many interesting projects, and I didn&#8217;t get to play with them all. I did get to work a bit on the Lunar Lander from last year, and this year it was finished successfully. My part was the PC game which interfaced with the microcontroller controlling the lander. As you probably guessed, it was written in Python.</p>
<p>This year, as promised, I worked on the Automatic Improviser. I worked on it with Ira Cherkes.</p>
<p>While the final version worked, it didn&#8217;t work well enough, and there is still much work to be done. Still, we had excellent progress.<br />
By the way, I know this subject has been tackled before, and I still wanted to try it myself, without reading too much literature about it.</p>
<p>One of the components of the system is a beat recognizer. My idea to discover the beat is simple: find the envelope (similar to removing AM modulation), and then find the low &#8220;frequency&#8221; of the envelope.<br />
Instead of doing a Fast Fourier Transform for beat recognition, we were advised that autocorellation will do the trick better and faster. However, when trying to autocorellate using scipy.signal.correlate we discovered that autocorellation was too slow for real time beat recognition, and certainly wasteful.</p>
<p>To solve this issue, we decided to first do peak detection on the envelope, and then autocorellate the peaks. Since there shouldn&#8217;t be too many peaks, this has the potential of being really quick. However, there was no standard function to do autocorellation of peaks, so we implemented it ourselves. We were pretty rushed, so we worked fast. Here&#8217;s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> autocorrelate_peaks<span style="color: black;">&#40;</span>peaks<span style="color: black;">&#41;</span>:
    peaks_dict = <span style="color: #008000;">dict</span><span style="color: black;">&#40;</span>peaks<span style="color: black;">&#41;</span>
    indexes = <span style="color: #008000;">set</span><span style="color: black;">&#40;</span>peaks_dict.<span style="color: black;">keys</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    deltas = <span style="color: #008000;">set</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> indexes:
        <span style="color: #ff7700;font-weight:bold;">for</span> j <span style="color: #ff7700;font-weight:bold;">in</span> indexes:
            <span style="color: #ff7700;font-weight:bold;">if</span> j<span style="color: #66cc66;">&gt;</span>i:
                <span style="color: #ff7700;font-weight:bold;">continue</span>
            deltas.<span style="color: black;">add</span><span style="color: black;">&#40;</span>i-j<span style="color: black;">&#41;</span>
&nbsp;
    result = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> d <span style="color: #ff7700;font-weight:bold;">in</span> deltas:
        moved = <span style="color: #008000;">set</span><span style="color: black;">&#40;</span>i+d <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> indexes<span style="color: black;">&#41;</span>
        to_mult = moved <span style="color: #66cc66;">&amp;</span> indexes
        <span style="color: #ff7700;font-weight:bold;">assert</span> to_mult <span style="color: #66cc66;">&lt;</span>= indexes
        s = <span style="color: #008000;">sum</span><span style="color: black;">&#40;</span>peaks_dict<span style="color: black;">&#91;</span>i-d<span style="color: black;">&#93;</span><span style="color: #66cc66;">*</span>peaks_dict<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span> <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> to_mult<span style="color: black;">&#41;</span>
        result<span style="color: black;">&#91;</span>d<span style="color: black;">&#93;</span> = s
    <span style="color: #ff7700;font-weight:bold;">return</span> result</pre></div></div>

<p>This function takes as input a list of tuples, each of the form (peak_index, peak_value), and returns a mapping between non-zero corellation offsets and their values.<br />
Here&#8217;s is a sample run:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">In <span style="color: black;">&#91;</span><span style="color: #ff4500;">7</span><span style="color: black;">&#93;</span>: autocorrelate_peaks<span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span>,<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span><span style="color: #ff4500;">7</span>,<span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">7</span><span style="color: black;">&#93;</span>: <span style="color: black;">&#123;</span><span style="color: #ff4500;">0</span>: <span style="color: #ff4500;">14</span>, <span style="color: #ff4500;">2</span>: <span style="color: #ff4500;">3</span>, <span style="color: #ff4500;">3</span>: <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">5</span>: <span style="color: #ff4500;">6</span><span style="color: black;">&#125;</span></pre></div></div>

<p>After implementing this function, our recognition loop was back to real-time, and we didn&#8217;t have to bother with optimizing again.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/math/fast-peak-autocorrelation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Checking the ulam spiral</title>
		<link>http://www.algorithm.co.il/blogs/math/checking-the-ulam-spiral/</link>
		<comments>http://www.algorithm.co.il/blogs/math/checking-the-ulam-spiral/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 11:11:04 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[prime numbers]]></category>
		<category><![CDATA[Ulam spiral]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=362</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/checking-the-ulam-spiral/' addthis:title='Checking the ulam spiral'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>In the following post, the Ulam spiral is described. It&#8217;s a very simple object &#8211; write down consecutive natural numbers starting from 41 in a square spiral. Curiously, the numbers on the diagonal are primes: Reading this post, I immediately &#8230; <a href="http://www.algorithm.co.il/blogs/math/checking-the-ulam-spiral/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/checking-the-ulam-spiral/' addthis:title='Checking the ulam spiral' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.futilitycloset.com/2009/09/11/the-ulam-spiral/">following post</a>, the Ulam spiral is described. It&#8217;s a very simple object &#8211; write down consecutive natural numbers starting from 41 in a square spiral. Curiously, the numbers on the diagonal are primes:</p>
<p><img src="http://www.algorithm.co.il/sitecode/ulam_spiral.png" alt="Ulam spiral" /></p>
<p>Reading this post, I immediately wanted to check how long this property holds. The original blog post suggests:</p>
<blockquote><p>Remarkably, all the numbers on the red diagonal are prime — even when the spiral is continued into a 20 × 20 square.</p></blockquote>
<p>Yet it doesn&#8217;t mention if it stops there or not. Without peeking (in Wikipedia), I wrote a simple program to check:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>
<span style="color: #ff7700;font-weight:bold;">import</span> psyco
psyco.<span style="color: black;">full</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
UP = <span style="color: #ff4500;">0</span>
LEFT = <span style="color: #ff4500;">1</span>
DOWN = <span style="color: #ff4500;">2</span>
RIGHT = <span style="color: #ff4500;">3</span>
&nbsp;
DIRECTIONS = <span style="color: black;">&#123;</span>UP: <span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, -<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>,
              LEFT: <span style="color: black;">&#40;</span>-<span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>,
              DOWN: <span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>,
              RIGHT: <span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span><span style="color: black;">&#125;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> generate_ulam_seq<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:
    start = <span style="color: #ff4500;">41</span>
    x = <span style="color: #ff4500;">0</span>
    y = <span style="color: #ff4500;">0</span>
    min_x = <span style="color: #ff4500;">0</span>
    max_x = <span style="color: #ff4500;">0</span>
    min_y = <span style="color: #ff4500;">0</span>
    max_y = <span style="color: #ff4500;">0</span>
    value = start
    direction = UP
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">yield</span> x, y, value
        value += <span style="color: #ff4500;">1</span>
        add_x, add_y = DIRECTIONS<span style="color: black;">&#91;</span>direction<span style="color: black;">&#93;</span>
        x, y = x + add_x, y + add_y
        <span style="color: #ff7700;font-weight:bold;">if</span> x <span style="color: #66cc66;">&lt;</span> min_x:
            direction = <span style="color: black;">&#40;</span>direction+<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span> <span style="color: #66cc66;">%</span> <span style="color: #ff4500;">4</span>
            min_x = x
        <span style="color: #ff7700;font-weight:bold;">if</span> x <span style="color: #66cc66;">&gt;</span> max_x:
            direction = <span style="color: black;">&#40;</span>direction+<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span> <span style="color: #66cc66;">%</span> <span style="color: #ff4500;">4</span>
            max_x = x
        <span style="color: #ff7700;font-weight:bold;">if</span> y <span style="color: #66cc66;">&lt;</span> min_y:
            direction = <span style="color: black;">&#40;</span>direction+<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span> <span style="color: #66cc66;">%</span> <span style="color: #ff4500;">4</span>
            min_y = y
        <span style="color: #ff7700;font-weight:bold;">if</span> y <span style="color: #66cc66;">&gt;</span> max_y:
            direction = <span style="color: black;">&#40;</span>direction+<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span> <span style="color: #66cc66;">%</span> <span style="color: #ff4500;">4</span>
            max_y = y
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> is_prime<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">all</span><span style="color: black;">&#40;</span>n<span style="color: #66cc66;">%</span>x <span style="color: #66cc66;">!</span>= <span style="color: #ff4500;">0</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span>, <span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>n<span style="color: #66cc66;">**</span><span style="color: #ff4500;">0.5</span><span style="color: black;">&#41;</span> + <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">for</span> x, y, v <span style="color: #ff7700;font-weight:bold;">in</span> generate_ulam_seq<span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> x == y <span style="color: #ff7700;font-weight:bold;">and</span> <span style="color: #ff7700;font-weight:bold;">not</span> is_prime<span style="color: black;">&#40;</span>v<span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">print</span> x, y, v
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Running it, we get:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #66cc66;">&gt;</span> ulam.<span style="color: black;">py</span> <span style="color: #ff4500;">10000</span>
<span style="color: #ff4500;">20</span> <span style="color: #ff4500;">20</span> <span style="color: #ff4500;">1681</span>
-<span style="color: #ff4500;">21</span> -<span style="color: #ff4500;">21</span> <span style="color: #ff4500;">1763</span>
<span style="color: #ff4500;">22</span> <span style="color: #ff4500;">22</span> <span style="color: #ff4500;">2021</span>
-<span style="color: #ff4500;">25</span> -<span style="color: #ff4500;">25</span> <span style="color: #ff4500;">2491</span>
<span style="color: #ff4500;">28</span> <span style="color: #ff4500;">28</span> <span style="color: #ff4500;">3233</span>
-<span style="color: #ff4500;">33</span> -<span style="color: #ff4500;">33</span> <span style="color: #ff4500;">4331</span>
<span style="color: #ff4500;">38</span> <span style="color: #ff4500;">38</span> <span style="color: #ff4500;">5893</span>
-<span style="color: #ff4500;">41</span> -<span style="color: #ff4500;">41</span> <span style="color: #ff4500;">6683</span>
<span style="color: #ff4500;">41</span> <span style="color: #ff4500;">41</span> <span style="color: #ff4500;">6847</span>
<span style="color: #ff4500;">42</span> <span style="color: #ff4500;">42</span> <span style="color: #ff4500;">7181</span>
-<span style="color: #ff4500;">44</span> -<span style="color: #ff4500;">44</span> <span style="color: #ff4500;">7697</span>
-<span style="color: #ff4500;">45</span> -<span style="color: #ff4500;">45</span> <span style="color: #ff4500;">8051</span>
-<span style="color: #ff4500;">46</span> -<span style="color: #ff4500;">46</span> <span style="color: #ff4500;">8413</span>
<span style="color: #ff4500;">48</span> <span style="color: #ff4500;">48</span> <span style="color: #ff4500;">9353</span></pre></div></div>

<p>So the property doesn&#8217;t hold for a very long time. Reading up <a href="http://en.wikipedia.org/wiki/Ulam_spiral">on Wikipedia</a>, it seems the Ulam spiral still has interesting properties related to primes in higher sizes. Maybe I&#8217;ll plot that one as well in a future post.</p>
<p>PS: Regarding primality testing, this is a cute, quick&#038;dirty one liner. In the range of numbers we&#8217;re discussing, it is &#8216;good enough&#8217;.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/math/checking-the-ulam-spiral/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Computing Large Determinants in Python</title>
		<link>http://www.algorithm.co.il/blogs/computer-science/computing-large-determinants-in-python/</link>
		<comments>http://www.algorithm.co.il/blogs/computer-science/computing-large-determinants-in-python/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 19:38:08 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[computer science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Research]]></category>
		<category><![CDATA[Float]]></category>
		<category><![CDATA[Fractions]]></category>
		<category><![CDATA[Matrix Determinants]]></category>
		<category><![CDATA[Numerical Analysis]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=176</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/computer-science/computing-large-determinants-in-python/' addthis:title='Computing Large Determinants in Python'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>Story: For my seminar work, I had to calculate the determinant of a large integer matrix. In this case, large meant n>=500. You might say that this isn&#8217;t very large and I would agree. However, it is large enough to &#8230; <a href="http://www.algorithm.co.il/blogs/computer-science/computing-large-determinants-in-python/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/computer-science/computing-large-determinants-in-python/' addthis:title='Computing Large Determinants in Python' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p><strong>Story:</strong><br />
For my seminar work, I had to calculate the determinant of a large integer matrix.<br />
In this case, large meant n>=500. You might say that this isn&#8217;t very large and I would agree. However, it is large enough to overflow a float and reach +inf. Reaching +inf is bad: once you do, you lose all the accuracy of the computation. Also, since determinant calculations use addition as well as subtraction, if +inf is reached in the middle of the calculation the value might never drop back, even if the determinant is a &#8220;small&#8221; number.</p>
<p>(Note: Even if the calculation hadn&#8217;t reached +inf, but just some very large floating point number, the same phenomenon could have occurred.)</p>
<p>As I said, my matrix was composed of integers. Since a determinant is a sum of multiples of matrix elements, you would expect such a determinant to be an integer as well. It would be nice to take advantage of that fact.</p>
<p>How should one compute such a determinant? Well, luckily Python has support for arbitrarily large integers. Let&#8217;s compute the determinant with them!<br />
Unfortunately, Python&#8217;s numpy computes determinants using LU decomposition, which uses division &#8211; hence, floating point values.<br />
Well, never mind, I know how to calculate a determinant, right?<br />
Ten minutes later the naive determinant calculation by minors was implemented, with one &#8220;minor&#8221; setback &#8211;  it takes O(n!) time.<br />
Googling for integer determinants yielded some articles about division free algorithms, which weren&#8217;t really easy to implement. There was one suggestion about using Rational numbers and Gauss Elimination, with pivots chosen to tame the growth of the nominator and denominator.</p>
<p>So, I hitched up a rational number class, using Python&#8217;s arbitrarily large integers as nominator and denominator. Then, I got some code to do Gauss Elimination, although my pivoting wasn&#8217;t the most fancy. This seemed to work, and I got my desired large determinants.</p>
<p><strong>Epilogue:</strong><br />
Not too long ago, I ran across <a href="http://code.google.com/p/mpmath/">mpmath</a>, a Python library for arbitrarily large floating point numbers. It is possible I could have used it instead of my own rational numbers. Next time I run into a relevant problem I&#8217;ll keep this library in mind.<br />
Also, an even shorter while ago, I became aware that since 2.6 Python boasts a fractions module. This will sure come in handy in the future.</p>
<p><strong>Code:</strong><br />
<a href="http://www.algorithm.co.il/sitecode/intdet.py">Available here</a>. If you intend to use it in Python 2.6 and above, I suggest replacing my Rational class with Python&#8217;s Fraction.<br />
(Note that I adapted this module to my needs. Therefore it has a timer that prints time estimations for computations, and it uses Psyco.)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/computer-science/computing-large-determinants-in-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fractal Memory Usage and a Big Number</title>
		<link>http://www.algorithm.co.il/blogs/computer-science/fractal-memory-usage-and-a-big-number/</link>
		<comments>http://www.algorithm.co.il/blogs/computer-science/fractal-memory-usage-and-a-big-number/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 18:31:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[computer science]]></category>
		<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[exponentiation]]></category>
		<category><![CDATA[memory usage]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=110</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/computer-science/fractal-memory-usage-and-a-big-number/' addthis:title='Fractal Memory Usage and a Big Number'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>In a previous post I said I&#8217;d talk about 4**(4**(4**4)). First, about the number. I first saw it mentioned in a math lesson back in high-school, when the teacher wanted to demonstrate estimation abilities. He wrote it on the board, &#8230; <a href="http://www.algorithm.co.il/blogs/computer-science/fractal-memory-usage-and-a-big-number/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/computer-science/fractal-memory-usage-and-a-big-number/' addthis:title='Fractal Memory Usage and a Big Number' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/my-bad-memory-high-load-and-python/">previous post</a> I said I&#8217;d talk about 4**(4**(4**4)).<br />
First, about the number. I first saw it mentioned in a math lesson back in high-school, when the teacher wanted to demonstrate estimation abilities.<br />
He wrote it on the board, like so:</p>
<p><strong><big><big>4<sup>4<sup>4<sup>4</sup></sup></sup></big></big></strong></p>
<p>and then asked students to estimate how big that number is. Turns out this number is much bigger than most students thought. (For comparison, <a href="http://en.wikipedia.org/wiki/Observable_universe#Matter_content">the number of atoms in the observable universe is 10<sup>80</sup></a>.)</p>
<p>Given that this number is so big, it should come as no surprise that computing it will consume all available memory.<br />
What is interesting is the way the memory is consumed:</p>
<p><img src="http://www.algorithm.co.il/sitecode/exp_memory.png"></p>
<p>(It died with a MemoryError just before the next &#8220;jump&#8221;.)</p>
<p>When I first saw this I was fascinated. To those interested it is generated by the long pow function in Python, implemented in longobject.c. According to the comment there, the algorithm is a left to right 5-ary exponentiation, taken from <a href="http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf">&#8220;Handbook of Applied Cryptography&#8221;</a>.<br />
In short, the simpler algorithm &#8220;left-to-right binary exponentiation&#8221; (used for smaller exponents) repeatedly squares the accumulator, and according to the binary digits of the exponents, multiplies it by the base. 5-ary exponentiation basically does the same thing, but in each iteration it &#8216;eats&#8217; five digits of the exponent instead of just one.</p>
<p>It might be very interesting to study algorithms and code according to their memory usage. Once at work I used a similar memory usage graph to optimize the memory usage of some algorithm that was eating too much memory. I don&#8217;t remember the details as it happened a few years ago, but I do remember that I recognized the &#8220;type of the memory eating&#8221;, which helped me to narrow the problem down to a specific area of code, where indeed the problem was located. (I consider this a case of programming-fu :)</p>
<p>Notes:<br />
1) The reason I&#8217;m talking about Python is because it has arbitrarily sized longs built-in.<br />
2) This graph was generated using Windows&#8217; task manager. On my Ubuntu machine it looks quite different, almost a straight line. Any guesses why?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/computer-science/fractal-memory-usage-and-a-big-number/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PyKoan &#8211; The Logic Game</title>
		<link>http://www.algorithm.co.il/blogs/math/pykoan-the-logic-game/</link>
		<comments>http://www.algorithm.co.il/blogs/math/pykoan-the-logic-game/#comments</comments>
		<pubDate>Sun, 01 Jun 2008 18:27:07 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Assembla]]></category>
		<category><![CDATA[Expression Trees]]></category>
		<category><![CDATA[Game]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[PyKoan]]></category>
		<category><![CDATA[Zendo]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=108</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/pykoan-the-logic-game/' addthis:title='PyKoan &#8211; The Logic Game'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>As you can probably tell, I&#8217;m back from my undeclared hiatus. I&#8217;ve got lots of stuff to talk about, and I&#8217;ll be starting with PyKoan, one small project I&#8217;ve been working on lately in my spare time. A few weeks &#8230; <a href="http://www.algorithm.co.il/blogs/math/pykoan-the-logic-game/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/pykoan-the-logic-game/' addthis:title='PyKoan &#8211; The Logic Game' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>As you can probably tell, I&#8217;m back from my undeclared hiatus. I&#8217;ve got lots of stuff to talk about, and I&#8217;ll be starting with PyKoan, one small project I&#8217;ve been working on lately in my spare time.</p>
<p>A few weeks ago I stumbled upon an <a href="http://en.wikipedia.org/wiki/Zendo_(game)">article in wikipedia</a>, regarding a logic game. This game fascinated me, especially because of the <a href="http://en.wikipedia.org/wiki/G%C3%B6del%2C_Escher%2C_Bach">&#8220;Godel Escher Bach&#8221;</a> connection. Quoting from Wikipedia:</p>
<blockquote><p><strong>Zendo</strong> is a game of inductive logic designed by Kory Heath in which one player (the &#8220;Master&#8221;) creates a rule for structures (&#8220;koans&#8221;) to follow, and the other players (the &#8220;Students&#8221;) try to discover it by building and studying various koans which follow or break the rule. The first student to correctly state the rule wins.</p></blockquote>
<p>As it happens I&#8217;m also taking a mathematical logic course this semester. Having read about the game, I wanted to write a similar computer game. Hence &#8211; PyKoan.</p>
<p>PyKoan is a game where the goal is to discover some logical rule, for example, &#8220;For each x holds x%2 == 0&#8243;. This rule is applied to a koan &#8211; a list of integers. An example koan that &#8220;has Buddha nature&#8221; (follows the rule) is [0,2,8]. One which doesn&#8217;t is [1].</p>
<p>To implement this idea, I wrote an implementation of an expression tree very similar to the one used in vial, but with a different implemented language. I also did some experimentation with the design. Since I&#8217;ve been talking a lot about expression trees without giving a full explanation, in a future post I&#8217;ll write about the implementation used in PyKoan.</p>
<p>So far I didn&#8217;t code a lot of the game, just the expression tree framework, and a simple rule builder. When using Python&#8217;s interactive prompt, one can get a taste of how the game might feel:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">In <span style="color: black;">&#91;</span><span style="color: #ff4500;">19</span><span style="color: black;">&#93;</span>: r = rulegen.<span style="color: black;">create_rule</span><span style="color: black;">&#40;</span>rulegen.<span style="color: black;">easy_grammer</span>, rulegen.<span style="color: black;">easy_grammer_start</span><span style="color: black;">&#41;</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">20</span><span style="color: black;">&#93;</span>: r.<span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">20</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">False</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">21</span><span style="color: black;">&#93;</span>: r.<span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">21</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">False</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">22</span><span style="color: black;">&#93;</span>: r.<span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">22</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">False</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">23</span><span style="color: black;">&#93;</span>: r.<span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">23</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">True</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">24</span><span style="color: black;">&#93;</span>: r.<span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span>,<span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">24</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">True</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">25</span><span style="color: black;">&#93;</span>: r.<span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span>,<span style="color: #ff4500;">2</span>,<span style="color: #ff4500;">3</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">25</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">True</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">26</span><span style="color: black;">&#93;</span>: r.<span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">3</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">26</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">False</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">27</span><span style="color: black;">&#93;</span>: r.<span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">4</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">27</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">False</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">28</span><span style="color: black;">&#93;</span>: <span style="color: #ff7700;font-weight:bold;">print</span> r
x exists such that x == <span style="color: #ff4500;">2</span></pre></div></div>

<p>Here is how I would generate such an expression manually:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">In <span style="color: black;">&#91;</span><span style="color: #ff4500;">3</span><span style="color: black;">&#93;</span>: <span style="color: #ff7700;font-weight:bold;">from</span> exptree <span style="color: #ff7700;font-weight:bold;">import</span> exps
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">4</span><span style="color: black;">&#93;</span>: exps.<span style="color: black;">Exists</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'x'</span>,exps.<span style="color: black;">Eq</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'x'</span>,<span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">4</span><span style="color: black;">&#93;</span>: exps.<span style="color: black;">Exists</span><span style="color: black;">&#40;</span>exps.<span style="color: black;">Var</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>, exps.<span style="color: black;">Eq</span><span style="color: black;">&#40;</span>exps.<span style="color: black;">Var</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>, exps.<span style="color: black;">Imm</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">5</span><span style="color: black;">&#93;</span>: <span style="color: #ff7700;font-weight:bold;">print</span> _
x exists such that x == <span style="color: #ff4500;">2</span></pre></div></div>

<p>The game has many interesting possibilities for research, for example, computer players. Other possibilities include &#8220;just&#8221; guessing koans (not the rule itself), creating interesting and playable rules, and so on. There&#8217;s a lot to do.</p>
<p>This time, instead of just publishing the (unfinished) code, I decided to do something different. I&#8217;ve opened a <a href="http://www.assembla.com/spaces/pykoan/">space in assembla</a>, with public read access. I&#8217;m opening this project for participation: if you want to join then leave a comment, or send me an email.</p>
<p>(Since Assembla seems to be going through some connectivity issues right now, <a href="http://www.algorithm.co.il/sitecode/pykoan.tar.gz">here&#8217;s a link</a> to a copy).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/math/pykoan-the-logic-game/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Two Mathematical Bugs</title>
		<link>http://www.algorithm.co.il/blogs/math/two-mathematical-bugs/</link>
		<comments>http://www.algorithm.co.il/blogs/math/two-mathematical-bugs/#comments</comments>
		<pubDate>Sat, 08 Mar 2008 17:20:22 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Geometry]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Line-Clipping]]></category>
		<category><![CDATA[random selection]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/index.php/programming/python/two-mathematical-bugs/</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/two-mathematical-bugs/' addthis:title='Two Mathematical Bugs'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>A few days ago, I discovered I had at least one, maybe two mathematical bugs. The first bug is in the line clipping algorithm. Here&#8217;s a quick reminder of what&#8217;s going on there: There are six points of interest: the &#8230; <a href="http://www.algorithm.co.il/blogs/math/two-mathematical-bugs/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/two-mathematical-bugs/' addthis:title='Two Mathematical Bugs' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>A few days ago, I discovered I had at least one, maybe two mathematical bugs. The first bug is in the <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/elegant-line-clipping-algorithm/">line clipping algorithm</a>. Here&#8217;s a quick reminder of what&#8217;s going on there:</p>
<blockquote><p>There are six points of interest: the four intersection points, and the two endpoints of the line. We sort the six points according to their parameter, and take the two innermost points as the endpoints of the clipped line. To check if the line is outside the box we make sure that the result points&#8217; parameters are between 0 and 1 (which correspond to the original endpoints).</p></blockquote>
<p>Turns out this is not always true &#8211; here&#8217;s a counter example:</p>
<p><img src="http://www.algorithm.co.il/sitecode/line_clipping2.png" Border="2" alt="Counter Example for the Line Clipping Algorithm" /></p>
<p>In the counter example you can see a line, whose endpoints lie between the intersections. The algorithm described above will say this line lies completely inside the box. Clearly this is not true. How do we fix this? Simple actually. We check for each intersection point whether or not it is on the edges of the clipping rectangle. If at most one point is on &#8211; our line is outside. I hope this is the end of it. It will require more rigorous testing.</p>
<p>The second bug was in <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/solution-for-the-random-selection-challenge/">my solution</a> to the <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/small-python-challenge-no-3-random-selection/">random selection challenge</a>. I wasn&#8217;t too sure of my solution, but I really liked it, as its code is rather elegant. So when meeting someone I used to work with, I told her about it. After thinking about my solution a bit, she said it is probably wrong, and gave me the reason: While the probability of a point x passing the first stage is indeed (proportional to) p(x), the probability of it passing the second stage is not 1 (or constant). I still need to think about this one, so no easy fix yet. I guess this reopens the challenge, so if anyone feels like writing a good proof or a counter example for my solution, I&#8217;d be happy to see it. I&#8217;ll be even happier to see a completely different solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/math/two-mathematical-bugs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Solution for the Random Selection Challenge</title>
		<link>http://www.algorithm.co.il/blogs/computer-science/solution-for-the-random-selection-challenge/</link>
		<comments>http://www.algorithm.co.il/blogs/computer-science/solution-for-the-random-selection-challenge/#comments</comments>
		<pubDate>Sat, 23 Feb 2008 23:50:23 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[computer science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Statistics]]></category>
		<category><![CDATA[Utility Functions]]></category>
		<category><![CDATA[challenge]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[probability distribution]]></category>
		<category><![CDATA[random selection]]></category>
		<category><![CDATA[Solution]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/index.php/programming/python/solution-for-the-random-selection-challenge/</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/computer-science/solution-for-the-random-selection-challenge/' addthis:title='Solution for the Random Selection Challenge'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>A few days ago, I wrote up two small Python Challenges. Several people have presented solutions for the first challenge, and I also posted my solution in the comments there. However, the second challenge remained unsolved, and I will present &#8230; <a href="http://www.algorithm.co.il/blogs/computer-science/solution-for-the-random-selection-challenge/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/computer-science/solution-for-the-random-selection-challenge/' addthis:title='Solution for the Random Selection Challenge' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>A few days ago, I <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/small-python-challenge-no-3-random-selection/">wrote up</a> two small Python Challenges. Several people have presented solutions for the first challenge, and I also posted my solution in the comments there.</p>
<p>However, the second challenge remained unsolved, and I will present a solution for it in this post.</p>
<p><span id="more-85"></span></p>
<p>First, a quick reminder:</p>
<blockquote><p>Given a continuous, solvable bell-shaped function p(x) in [a,b], and a uniform random selection function (such as random.random()), write a function that will yield a distribution proportional to p(x)</p></blockquote>
<p>The requirement that p(x) be solvable is critical for the solution.<br />
As an example for such a function, consider y=e^(-x**2), in [-1,1]. It is bell shaped, and the solutions are given by ,[ -sqrt(-log(y)), sqrt(-log(y)) ].</p>
<p>I&#8217;ll start with the code for the solution, as it might be clearer for the less mathematically inclined:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> random_dist<span style="color: black;">&#40;</span>dist_func, dist_solve_func<span style="color: black;">&#41;</span>:
    y = <span style="color: #dc143c;">random</span>.<span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    a,b = dist_solve_func<span style="color: black;">&#40;</span>y<span style="color: black;">&#41;</span>
    x = a+<span style="color: #dc143c;">random</span>.<span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: black;">&#40;</span>b-a<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> x</pre></div></div>

<p><strong>Why does this work? (warning: math ahead)</strong></p>
<p>We need to generate a probability distribution proportional to p(x).</p>
<p>(Note: the distribution will be exact (and not proportional) only if the integral of p(x) in [a,b] is 1. This is equivalent to requiring that the probabilities sum to 1 in the discrete case. We&#8217;ll call such a function p(x) a standard distribution function.)</p>
<p>To generate the distribution, we note that if we select at random a y in [0,1], for each x, The probability of p(x)>=y is p(x). For example, if p(x) = 0.5, then given a random number 0<=y<=1, the condition p(x) >= y will happen exactly half the time.<br />
(If p(x) is a non-standard function, then the probability is instead only proportional to p(x))</p>
<p>Now, solving the problem is easy &#8211; we select a y at random. We find all the x such that p(x) >= y. We select one of these x at random, and the resulting x will be distributed proportionally to p(x). Selecting such an x at random becomes easy because of our requirements that p(x) be bell shaped and solvable. Given x0, x1 such that y=p(x0) and y=p(x1), we know that all x such that p(x)>y lie in between these two solutions.<br />
Hence, the second random() call chooses an x in the range [x0, x1].</p>
<p>In the following illustration of a bell function, two areas are marked. One is the result of selecting y=0.3, and the other of selecting y=0.2. The second area is indeed larger than the first, and contains the first area, as expected of a bell function. Thus, each x will be selected proportionally to p(x).</p>
<p><img src="http://www.algorithm.co.il/sitecode/random_dist3.png" border="2" alt="Illustration of a bell function" /></p>
<p><strong>Empirical Proof of the solution:</strong><br />
Again, code speaks louder (but more tersely) than words.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#Choose a lot of random numbers</span>
<span style="color: #808080; font-style: italic;">#distributed proportionally to p</span>
result = <span style="color: black;">&#91;</span>random_select.<span style="color: black;">random_dist</span><span style="color: black;">&#40;</span>random_select.<span style="color: black;">p</span>,
                                    random_select.<span style="color: black;">solve_p</span><span style="color: black;">&#41;</span>
                <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10000</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
<span style="color: #808080; font-style: italic;">#divide the numbers to buckets:</span>
<span style="color: #808080; font-style: italic;">#truncate to 2 digits after the point</span>
d = <span style="color: black;">&#91;</span>numpy.<span style="color: black;">floor</span><span style="color: black;">&#40;</span>x<span style="color: #66cc66;">*</span><span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> result<span style="color: black;">&#93;</span>
h = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#count how many numbers ended up in each bucket</span>
<span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> d:
    h<span style="color: black;">&#91;</span>x<span style="color: black;">&#93;</span> = h.<span style="color: black;">get</span><span style="color: black;">&#40;</span>x,<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>+<span style="color: #ff4500;">1.0</span>/<span style="color: #008000;">len</span><span style="color: black;">&#40;</span>result<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#plot the 'height' of each bucket</span>
xvals = result
yvals = <span style="color: black;">&#91;</span>h<span style="color: black;">&#91;</span>numpy.<span style="color: black;">floor</span><span style="color: black;">&#40;</span>x<span style="color: #66cc66;">*</span><span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> result<span style="color: black;">&#93;</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;">#plot our original distribution,</span>
<span style="color: #808080; font-style: italic;">#aligned with the graph (but not exactly).</span>
avg = <span style="color: #008000;">sum</span><span style="color: black;">&#40;</span>yvals<span style="color: black;">&#41;</span>/<span style="color: #008000;">len</span><span style="color: black;">&#40;</span>yvals<span style="color: black;">&#41;</span>
m = <span style="color: #008000;">max</span><span style="color: black;">&#40;</span>yvals<span style="color: black;">&#41;</span>
xvals2 = numpy.<span style="color: black;">arange</span><span style="color: black;">&#40;</span>-<span style="color: #ff4500;">3</span>,<span style="color: #ff4500;">3</span>,<span style="color: #ff4500;">0.1</span><span style="color: black;">&#41;</span>
yvals2 = <span style="color: black;">&#91;</span>random_select.<span style="color: black;">p</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span>m <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> xvals2<span style="color: black;">&#93;</span>
&nbsp;
pylab.<span style="color: black;">plot</span><span style="color: black;">&#40;</span>xvals, yvals, <span style="color: #483d8b;">&quot;r+&quot;</span><span style="color: black;">&#41;</span>
pylab.<span style="color: black;">plot</span><span style="color: black;">&#40;</span>xvals2, yvals2, <span style="color: #483d8b;">&quot;b-&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>This code generates the following graph, which proves this solution works:<br />
<img src="http://www.algorithm.co.il/sitecode/random_dist2.png" border="2" alt="Proof of the random selection solution" /></p>
<p><strong>A few thoughts</strong><br />
This problem may be seen as a standard computer science &#8216;computation with an oracle&#8217; problem. Here, our oracle is random.random(), and we want to compute a function. In these kind of cases, it is customary to ask:<br />
1. What may be generally computed with this oracle?<br />
2. Given a specific problem, what is the minimum number of oracle calls required to solve it?</p>
<p>The answer to the first question is the easier one &#8211; we can generalize this solution to any continuous solvable distribution p(x) in [a,b]. Since the same reasoning applies &#8211; we just need to be able to find all x such that p(x)>y given a specific y. If our solutions are [x,y,z,w], and p(a) &lt; y, then we need to select an x from [x,y] U [z,w].This is easily achieved in any number of ways. For example, select one of the ranges with the discrete selection (the first challenge), and then select an x from the selected range.</p>
<p>The answer to the second question is a bit more complicated. The solution described above for bell shaped curves solves the problem with just two calls to random(). To beat it, a solution with just one call is required. This seems daunting at first, but it is possible, even if complicated. What we want is a function that will convert the uniform density of random()&#8217;s output to our distribution&#8217;s density.<br />
Consider the graph of a function as a path. If we select a random point on the path, and check its x-coordinate, we&#8217;ll see that the probability distribution of the x&#8217;s proportional to the absolute inclination of the function at that point. Since inclination is equivalent to the differential, if we do this process to the integral of our distribution function, we&#8217;ll get the required distribution.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/computer-science/solution-for-the-random-selection-challenge/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with Matrices</title>
		<link>http://www.algorithm.co.il/blogs/math/fun-with-matrices/</link>
		<comments>http://www.algorithm.co.il/blogs/math/fun-with-matrices/#comments</comments>
		<pubDate>Wed, 20 Feb 2008 23:36:33 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Newton-Raphson]]></category>
		<category><![CDATA[numpy]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/index.php/programming/python/fun-with-matrices/</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/fun-with-matrices/' addthis:title='Fun with Matrices'  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>I&#8217;ll let the code speak for itself: In &#91;81&#93;: m = Matrix&#40;array&#40;&#91;&#91;1.0,1.0&#93;,&#91;0.0,1.0&#93;&#93;&#41;&#41; &#160; In &#91;82&#93;: def my_sqrt&#40;x, num_iters&#41;: ....: r = 0.5*x ....: for i in xrange&#40;num_iters&#41;: ....: r = 0.5*&#40;r+x/r&#41; ....: return r ....: &#160; In &#91;83&#93;: m*m Out&#91;83&#93;: &#8230; <a href="http://www.algorithm.co.il/blogs/math/fun-with-matrices/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style " addthis:url='http://www.algorithm.co.il/blogs/math/fun-with-matrices/' addthis:title='Fun with Matrices' ><a href="http://addthis.com/bookmark.php?v=250&#38;username=xa-4d2b47597ad291fb" class="addthis_button_compact">Share</a><span class="addthis_separator">&#124;</span><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a></div>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ll let the code speak for itself:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">In <span style="color: black;">&#91;</span><span style="color: #ff4500;">81</span><span style="color: black;">&#93;</span>: m = Matrix<span style="color: black;">&#40;</span><span style="color: #dc143c;">array</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1.0</span>,<span style="color: #ff4500;">1.0</span><span style="color: black;">&#93;</span>,<span style="color: black;">&#91;</span><span style="color: #ff4500;">0.0</span>,<span style="color: #ff4500;">1.0</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">82</span><span style="color: black;">&#93;</span>: <span style="color: #ff7700;font-weight:bold;">def</span> my_sqrt<span style="color: black;">&#40;</span>x, num_iters<span style="color: black;">&#41;</span>:
   ....:     r = <span style="color: #ff4500;">0.5</span><span style="color: #66cc66;">*</span>x
   ....:     <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>num_iters<span style="color: black;">&#41;</span>:
   ....:             r = <span style="color: #ff4500;">0.5</span><span style="color: #66cc66;">*</span><span style="color: black;">&#40;</span>r+x/r<span style="color: black;">&#41;</span>
   ....:     <span style="color: #ff7700;font-weight:bold;">return</span> r
   ....:
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">83</span><span style="color: black;">&#93;</span>: m<span style="color: #66cc66;">*</span>m
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">83</span><span style="color: black;">&#93;</span>:
<span style="color: #dc143c;">array</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: black;">&#91;</span> <span style="color: #ff4500;">1</span>.,  <span style="color: #ff4500;">2</span>.<span style="color: black;">&#93;</span>,
       <span style="color: black;">&#91;</span> <span style="color: #ff4500;">0</span>.,  <span style="color: #ff4500;">1</span>.<span style="color: black;">&#93;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">84</span><span style="color: black;">&#93;</span>: my_sqrt<span style="color: black;">&#40;</span>m<span style="color: #66cc66;">*</span>m, <span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">84</span><span style="color: black;">&#93;</span>:
<span style="color: #dc143c;">array</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: black;">&#91;</span> <span style="color: #ff4500;">1</span>.,  <span style="color: #ff4500;">1</span>.<span style="color: black;">&#93;</span>,
       <span style="color: black;">&#91;</span> <span style="color: #ff4500;">0</span>.,  <span style="color: #ff4500;">1</span>.<span style="color: black;">&#93;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
&nbsp;
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">85</span><span style="color: black;">&#93;</span>: m
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">85</span><span style="color: black;">&#93;</span>:
<span style="color: #dc143c;">array</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: black;">&#91;</span> <span style="color: #ff4500;">1</span>.,  <span style="color: #ff4500;">1</span>.<span style="color: black;">&#93;</span>,
       <span style="color: black;">&#91;</span> <span style="color: #ff4500;">0</span>.,  <span style="color: #ff4500;">1</span>.<span style="color: black;">&#93;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>It&#8217;s always fun to see the math work out. At first when I learned that e^A for a matrix A may also be defined using the Taylor series in the usual way, I was really amazed. It still amazes me that this stuff works out so well. This is another kind of beauty.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/math/fun-with-matrices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

