<?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>Zen and the Art of Programming &#187; Mathematics</title>
	<atom:link href="http://programmingzen.com/category/mathematics/feed/" rel="self" type="application/rss+xml" />
	<link>http://programmingzen.com</link>
	<description>By Antonio Cangiano, Software Engineer &#38; Technical Evangelist at IBM</description>
	<lastBuildDate>Wed, 21 Jul 2010 22:12:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Monte Carlo simulation of the Monty Hall Problem in Ruby and Python</title>
		<link>http://programmingzen.com/2009/01/01/monte-carlo-simulation-of-the-monty-hall-problem-in-ruby-and-python/</link>
		<comments>http://programmingzen.com/2009/01/01/monte-carlo-simulation-of-the-monty-hall-problem-in-ruby-and-python/#comments</comments>
		<pubDate>Thu, 01 Jan 2009 22:55:17 +0000</pubDate>
		<dc:creator>Antonio Cangiano</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://antoniocangiano.com/?p=524</guid>
		<description><![CDATA[Reading Jeff Atwood&#8217;s post The Problem of the Unfinished Game, reminded me of a similar problem. The Monty Hall Problem is a well known probability puzzle that has tricked many people. In fact, if you are not familiar with it already, chances are that you&#8217;ll get it wrong. And you would be in good company [...]]]></description>
			<content:encoded><![CDATA[<p>Reading Jeff Atwood&#8217;s post <a href="http://www.codinghorror.com/blog/archives/001203.html">The Problem of the Unfinished Game</a>, reminded me of a similar problem. The Monty Hall Problem is a well known probability puzzle that has tricked many people. In fact, if you are not familiar with it already, chances are that you&#8217;ll get it wrong. And you would be in good company along with many mathematicians and physicists, including the great mathematician, Paul Erdos. This puzzle is loosely based on the television show <em>Let&#8217;s Make a Deal</em>, and is equivalent to some much older puzzles you may be familiar with (e.g. the three prisoners problem). In its simplest form, it asks the following question:</p>
<blockquote><p>Suppose you&#8217;re on a game show, and you&#8217;re given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what&#8217;s behind the doors, opens another door, say No. 3, which has a goat. He then says to you, &#8220;Do you want to pick door No. 2?&#8221; Is it to your advantage to switch your choice?</p></blockquote>
<p>This definition of the problem is admittedly ambiguous. Thankfully Wikipedia points us towards a more exact definition:</p>
<blockquote><p>Suppose you&#8217;re on a game show and you&#8217;re given the choice of three doors. Behind one door is a car; behind the others, goats [that is, booby prizes]. The car and the goats were placed randomly behind the doors before the show. The rules of the game show are as follows: After you have chosen a door, the door remains closed for the time being. The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it. If both remaining doors have goats behind them, he chooses one randomly. After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door. Imagine that you chose Door 1 and the host opens Door 3, which has a goat. He then asks you &#8220;Do you want to switch to Door Number 2?&#8221; Is it to your advantage to change your choice?</p></blockquote>
<p align="center"><img src="http://antoniocangiano.com/images/monty.gif" alt="The Monty Hall Problem" /></p>
<p>Think about it for a moment, then read on. To answer this question, most people will try to determine which of the two possible outcomes has a higher probability. Problems arise when trying to correctly calculate the probability of these two events though. There are two closed doors and the car could be behind either of them. Hence, most people&#8217;s &#8220;common sense&#8221; and psychology leads them to believe that there is a 50% chance that the car is behind the initially selected door, and 50% that it&#8217;s behind the other closed door that was offered up by Monty. Initially it would seem that switching or staying with the first choice doesn&#8217;t really make a difference.</p>
<p>Unfortunately that&#8217;s not the right answer. The correct answer is that there is a two out of three chance of winning by switching to the other door; so switching is always to your advantage. This result is considered to be a paradox because it&#8217;s very counterintuitive to the way that many people think. It is in fact so counterintuitive that most people will argue with you in an attempt to convince you otherwise. I invite you to check out the <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem">Wikipedia entry</a> on the problem/paradox, to read a step-by-step explanation with figures about why switching gives you about 66.7% chance of winning the car and why staying with the initial choice gives you only a 33.3% success rate.</p>
<p>When you make your first choice your probability of winning the car is only 1/3. If you decide to switch, you will win only if the first choice you made was wrong. And since your first choice came with a 2 out of 3 chance of picking a goat, switching will then (logically) give you 2/3 chance of winning. Another easy way to come to intuitively accept this surprising result, is to wildly exaggerate the terms of the problem. If there were a billion doors, you picked one, and then Monty proceeded to open up all the remaining doors but one, we&#8217;d have a situation where it would be extremely unlikely that you picked the right door at the beginning, while it would be extremely likely that the remaining door was the one that was concealing the car.</p>
<p>Even after reading several explanations and aids to understand these results, there are still people who are skeptical or refuse to believe them. Let&#8217;s verify the outcome with a simulation.</p>
<p>What you find below is a quick Ruby script that I wrote to run a Monte Carlo Simulation of the Monty Hall problem/paradox. It runs the game a million times and then measures how many times the player won by sticking with their first choice, and how many times switching would have led to winning the car.</p>
<div class="highlight">
<pre><span class="c1">#!/usr/bin/env ruby -w</span>

<span class="c1"># Monte Carlo simulation for the Monty Hall Problem:</span>
<span class="c1"># http://en.wikipedia.org/wiki/Monty_Hall_problem</span>

<span class="cm">=begin</span>
<span class="cm">When using a Ruby version older than 1.8.7</span>
<span class="cm">define the following two methods:</span>

<span class="cm">  class Array</span>
<span class="cm">    def shuffle</span>
<span class="cm">      self.sort_by { rand }</span>
<span class="cm">    end</span>
<span class="cm">    </span>
<span class="cm">    def choice</span>
<span class="cm">      self.shuffle.first</span>
<span class="cm">    end</span>
<span class="cm">  end</span>
<span class="cm">=end</span>

<span class="c1"># Utility class for the simulation of a single Monty Hall game.</span>
<span class="k">class</span> <span class="nc">MontyHall</span>
  <span class="k">def</span> <span class="nf">initialize</span>
    <span class="vi">@doors</span> <span class="o">=</span> <span class="o">[</span><span class="s1">&#39;car&#39;</span><span class="p">,</span> <span class="s1">&#39;goat&#39;</span><span class="p">,</span> <span class="s1">&#39;goat&#39;</span><span class="o">].</span><span class="n">shuffle</span>
  <span class="k">end</span>

  <span class="c1"># Return a number representing the player&#39;s first choice.</span>
  <span class="k">def</span> <span class="nf">pick_door</span>
    <span class="k">return</span> <span class="nb">rand</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="c1"># Return the index of the door opened by the host.</span>
  <span class="c1"># This cannot represent a door hiding a car or the player&#39;s chosen door.</span>
  <span class="k">def</span> <span class="nf">reveal_door</span><span class="p">(</span><span class="n">pick</span><span class="p">)</span>
    <span class="n">available_doors</span> <span class="o">=</span> <span class="o">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="o">]</span>
    <span class="n">available_doors</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">pick</span><span class="p">)</span>
    <span class="n">available_doors</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="vi">@doors</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="s1">&#39;car&#39;</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">available_doors</span><span class="o">.</span><span class="n">choice</span>
  <span class="k">end</span>

  <span class="c1"># Return true if the player won by staying</span>
  <span class="c1"># with their first choice, false otherwise.</span>
  <span class="k">def</span> <span class="nf">staying_wins?</span><span class="p">(</span><span class="n">pick</span><span class="p">)</span>
    <span class="n">won?</span><span class="p">(</span><span class="n">pick</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="c1"># Return true if the player won by switching, false otherwise.</span>
  <span class="k">def</span> <span class="nf">switching_wins?</span><span class="p">(</span><span class="n">pick</span><span class="p">,</span> <span class="n">open_door</span><span class="p">)</span>
    <span class="n">switched_pick</span> <span class="o">=</span> <span class="p">(</span><span class="o">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="o">]</span> <span class="o">-</span> <span class="o">[</span><span class="n">open_door</span><span class="p">,</span> <span class="n">pick</span><span class="o">]</span><span class="p">)</span><span class="o">.</span><span class="n">first</span>
    <span class="n">won?</span><span class="p">(</span><span class="n">switched_pick</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="kp">private</span>

  <span class="c1"># Return true if the player&#39;s final pick hides a car, false otherwise.</span>
  <span class="k">def</span> <span class="nf">won?</span><span class="p">(</span><span class="n">pick</span><span class="p">)</span>
    <span class="vi">@doors</span><span class="o">[</span><span class="n">pick</span><span class="o">]</span> <span class="o">==</span> <span class="s1">&#39;car&#39;</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="k">if</span> <span class="bp">__FILE__</span> <span class="o">==</span> <span class="vg">$0</span>
  <span class="no">ITERATIONS</span> <span class="o">=</span> <span class="p">(</span><span class="no">ARGV</span><span class="o">.</span><span class="n">shift</span> <span class="o">||</span> <span class="mi">1_000_000</span><span class="p">)</span><span class="o">.</span><span class="n">to_i</span>
  <span class="n">staying</span> <span class="o">=</span> <span class="mi">0</span>
  <span class="n">switching</span> <span class="o">=</span> <span class="mi">0</span>

  <span class="no">ITERATIONS</span><span class="o">.</span><span class="n">times</span> <span class="k">do</span>
    <span class="n">mh</span> <span class="o">=</span> <span class="no">MontyHall</span><span class="o">.</span><span class="n">new</span>
    <span class="n">picked</span> <span class="o">=</span> <span class="n">mh</span><span class="o">.</span><span class="n">pick_door</span>
    <span class="n">revealed</span> <span class="o">=</span> <span class="n">mh</span><span class="o">.</span><span class="n">reveal_door</span><span class="p">(</span><span class="n">picked</span><span class="p">)</span>
    <span class="n">staying</span> <span class="o">+=</span> <span class="mi">1</span> <span class="k">if</span> <span class="n">mh</span><span class="o">.</span><span class="n">staying_wins?</span><span class="p">(</span><span class="n">picked</span><span class="p">)</span>
    <span class="n">switching</span> <span class="o">+=</span> <span class="mi">1</span> <span class="k">if</span> <span class="n">mh</span><span class="o">.</span><span class="n">switching_wins?</span><span class="p">(</span><span class="n">picked</span><span class="p">,</span> <span class="n">revealed</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="n">staying_rate</span> <span class="o">=</span> <span class="p">(</span><span class="n">staying</span><span class="o">.</span><span class="n">to_f</span> <span class="o">/</span> <span class="no">ITERATIONS</span><span class="p">)</span> <span class="o">*</span> <span class="mi">100</span>
  <span class="n">switching_rate</span> <span class="o">=</span> <span class="p">(</span><span class="n">switching</span><span class="o">.</span><span class="n">to_f</span> <span class="o">/</span> <span class="no">ITERATIONS</span><span class="p">)</span> <span class="o">*</span> <span class="mi">100</span>

  <span class="nb">puts</span> <span class="s2">&quot;Staying: </span><span class="si">#{</span><span class="n">staying_rate</span><span class="si">}</span><span class="s2">%.&quot;</span>
  <span class="nb">puts</span> <span class="s2">&quot;Switching: </span><span class="si">#{</span><span class="n">switching_rate</span><span class="si">}</span><span class="s2">%.&quot;</span>
<span class="k">end</span>
</pre>
</div>
<p>And here is an &#8220;equivalent&#8221; version I wrote in Python:</p>
<div class="highlight">
<pre><span class="c">#!/usr/bin/env python</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">Monte Carlo simulation for the Monty Hall Problem:</span>
<span class="sd">http://en.wikipedia.org/wiki/Monty_Hall_problem.</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">randrange</span><span class="p">,</span> <span class="n">shuffle</span><span class="p">,</span> <span class="n">choice</span>

<span class="n">DOORS</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;car&#39;</span><span class="p">,</span> <span class="s">&#39;goat&#39;</span><span class="p">,</span> <span class="s">&#39;goat&#39;</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">pick_door</span><span class="p">():</span>
    <span class="sd">&quot;&quot;&quot;Return a number representing the player&#39;s first choice.&quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">randrange</span><span class="p">(</span><span class="mf">3</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">reveal_door</span><span class="p">(</span><span class="n">pick</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return the index of the door opened by the host.</span>
<span class="sd">    This cannot be a door hiding a car or the player&#39;s chosen door.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">all_doors</span> <span class="o">=</span> <span class="n">set</span><span class="p">([</span><span class="mf">0</span><span class="p">,</span> <span class="mf">1</span><span class="p">,</span> <span class="mf">2</span><span class="p">])</span>
    <span class="n">unavailable_doors</span> <span class="o">=</span> <span class="n">set</span><span class="p">([</span><span class="n">DOORS</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="s">&#39;car&#39;</span><span class="p">),</span> <span class="n">pick</span><span class="p">])</span>
    <span class="n">available_doors</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">all_doors</span> <span class="o">-</span> <span class="n">unavailable_doors</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">choice</span><span class="p">(</span><span class="n">available_doors</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">staying_wins</span><span class="p">(</span><span class="n">pick</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return True if the player won by staying</span>
<span class="sd">    with their first choice, False otherwise.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">won</span><span class="p">(</span><span class="n">pick</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">switching_wins</span><span class="p">(</span><span class="n">pick</span><span class="p">,</span> <span class="n">open_door</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return True if the player won by switching,</span>
<span class="sd">    False otherwise.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">other_doors</span> <span class="o">=</span> <span class="n">set</span><span class="p">([</span><span class="n">pick</span><span class="p">,</span> <span class="n">open_door</span><span class="p">])</span>
    <span class="n">switched_pick</span> <span class="o">=</span> <span class="p">(</span><span class="n">set</span><span class="p">([</span><span class="mf">0</span><span class="p">,</span> <span class="mf">1</span><span class="p">,</span> <span class="mf">2</span><span class="p">])</span> <span class="o">-</span> <span class="n">other_doors</span><span class="p">)</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">won</span><span class="p">(</span><span class="n">switched_pick</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">won</span><span class="p">(</span><span class="n">pick</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return True if the player&#39;s final pick hides a car,</span>
<span class="sd">    False otherwise.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">DOORS</span><span class="p">[</span><span class="n">pick</span><span class="p">]</span> <span class="o">==</span> <span class="s">&#39;car&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">(</span><span class="n">iterations</span><span class="o">=</span><span class="mf">1000000</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Run the main simulation as many</span>
<span class="sd">    times as specified by the function argument.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">shuffle</span><span class="p">(</span><span class="n">DOORS</span><span class="p">)</span>

    <span class="n">switching</span> <span class="o">=</span> <span class="mf">0</span>
    <span class="n">staying</span> <span class="o">=</span> <span class="mf">0</span>

    <span class="k">for</span> <span class="n">dummy</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iterations</span><span class="p">):</span>
        <span class="n">picked</span> <span class="o">=</span> <span class="n">pick_door</span><span class="p">()</span>
        <span class="n">revealed</span> <span class="o">=</span> <span class="n">reveal_door</span><span class="p">(</span><span class="n">picked</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">staying_wins</span><span class="p">(</span><span class="n">picked</span><span class="p">):</span>
            <span class="n">staying</span> <span class="o">+=</span> <span class="mf">1</span>
        <span class="k">if</span> <span class="n">switching_wins</span><span class="p">(</span><span class="n">picked</span><span class="p">,</span> <span class="n">revealed</span><span class="p">):</span>
            <span class="n">switching</span> <span class="o">+=</span> <span class="mf">1</span>

    <span class="n">staying_rate</span> <span class="o">=</span> <span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">staying</span><span class="p">)</span> <span class="o">/</span> <span class="n">iterations</span><span class="p">)</span> <span class="o">*</span> <span class="mf">100</span>
    <span class="n">switching_rate</span> <span class="o">=</span> <span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">switching</span><span class="p">)</span> <span class="o">/</span> <span class="n">iterations</span><span class="p">)</span> <span class="o">*</span> <span class="mf">100</span>

    <span class="k">print</span> <span class="s">&quot;Staying: </span><span class="si">%f%%</span><span class="s">&quot;</span> <span class="o">%</span> <span class="n">staying_rate</span>
    <span class="k">print</span> <span class="s">&quot;Switching: </span><span class="si">%f%%</span><span class="s">&quot;</span> <span class="o">%</span> <span class="n">switching_rate</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="o">==</span> <span class="mf">2</span><span class="p">:</span>
        <span class="n">main</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">]))</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">main</span><span class="p">()</span>
</pre>
</div>
<p>Even if you are not familiar with Ruby or Python, you may be able to understand what&#8217;s going on here. The main body of the program emulates the game and keeps track of the number of victories when the player sticks with their initial choice, and when they switch. Notice that this code intentionally tries not to be clever, in order not to annoy &#8220;skeptical&#8221; people.</p>
<p>There are many points in the code where correct assumptions about the problem would lead us to code that is faster and much more compact. For example, if the player wins a given game by sticking with his first answer, it&#8217;s obvious that switching would have made him lose. We could just calculate the difference between 100 and the success rate of staying with the first choice, and we&#8217;d obtain the success rate for switching. But here we are trying to simulate the problem as faithfully as possible and abstract as little as necessary.</p>
<p>As always with Monte Carlo Simulations, the outcome is slightly variable during each run since it depends on random input; but by the law of large numbers, it will very slowly converge to the expected values (despite the pseudo-randomness used here). For example, when I executed the code above for the first time on my machine, I obtained the following:</p>
<pre>
Staying: 33.382%.
Switching: 66.618%.
</pre>
<p>The results of this simulation should be enough to convince you that the theoretical results are actually true; we are easily fooled, and the mathematicians who got it right were not making stuff up. <img src='http://programmingzen.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Happy New Year to my readers, I wish you all the best for a happy, successful 2009!</p>
]]></content:encoded>
			<wfw:commentRss>http://programmingzen.com/2009/01/01/monte-carlo-simulation-of-the-monty-hall-problem-in-ruby-and-python/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>How to parse decimal numbers within a string</title>
		<link>http://programmingzen.com/2006/02/05/how-to-parse-numbers-in-a-string/</link>
		<comments>http://programmingzen.com/2006/02/05/how-to-parse-numbers-in-a-string/#comments</comments>
		<pubDate>Sun, 05 Feb 2006 11:40:00 +0000</pubDate>
		<dc:creator>Antonio Cangiano</dc:creator>
				<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Quick Tips]]></category>

		<guid isPermaLink="false">http://72.52.169.158/~antonioc/2006/02/05/how-to-parse-numbers-in-a-string/</guid>
		<description><![CDATA[INPUT: a string containing decimal numbers. OUTPUT: an array containing all the decimal numbers within the given string. You can accomplish this task very quickly with the String#scan method and the right Regular Expression (regex). Given a string s, you can use: numbers = s.scan /[-+]?\d*\.?\d+/ numbers will be an array whose elements are the [...]]]></description>
			<content:encoded><![CDATA[<p><span class="caps">INPUT</span>: a string containing decimal numbers.</p>
<p><span class="caps">OUTPUT</span>: an array containing all the decimal numbers within the given string.</p>
<p>You can accomplish this task very quickly with the <strong>String#scan</strong> method and the right <strong>Regular Expression</strong> (regex).</p>
<p>Given a string <strong>s</strong>, you can use:</p>
<div class="typocode">
<pre><code class="typocode_ruby "><span class="ident">numbers</span> <span class="punct">=</span> <span class="ident">s</span><span class="punct">.</span><span class="ident">scan</span> <span class="punct">/[-+]</span><span class="char">?\d</span><span class="punct">*\.</span><span class="char">?\d</span><span class="punct">+/</span><span class="regex"></span></code></pre>
</div>
<p><strong>numbers</strong> will be an array whose elements are the decimal numbers within the string <strong>s</strong>. Note how the regex considers the possible + or &#8211; signs in front of the numbers.</p>
<p>If you also wish to match <strong>floating point numbers with exponents</strong> (scientific notation, e.g. 2.54.e-07), then use the following:</p>
<div class="typocode">
<pre><code class="typocode_ruby "><span class="ident">numbers</span> <span class="punct">=</span> <span class="ident">s</span><span class="punct">.</span><span class="ident">scan</span> <span class="punct">/[-+]</span><span class="char">?\d</span><span class="punct">*\.</span><span class="char">?\d</span><span class="punct">+([</span><span class="ident">eE</span><span class="punct">][-+]</span><span class="char">?\d</span><span class="punct">+)</span><span class="char">?/</span> </code></pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://programmingzen.com/2006/02/05/how-to-parse-numbers-in-a-string/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Solving mathematical problems with Ruby</title>
		<link>http://programmingzen.com/2006/01/30/solving-mathematical-problems-with-ruby/</link>
		<comments>http://programmingzen.com/2006/01/30/solving-mathematical-problems-with-ruby/#comments</comments>
		<pubDate>Mon, 30 Jan 2006 18:50:00 +0000</pubDate>
		<dc:creator>Antonio Cangiano</dc:creator>
				<category><![CDATA[Mathematics]]></category>

		<guid isPermaLink="false">http://72.52.169.158/~antonioc/2006/01/30/solving-mathematical-problems-with-ruby/</guid>
		<description><![CDATA[A couple of weeks ago I&#8217;ve discovered a very interesting and addictive website MathsChallenge.net . They have a section called Project Euler where participants can try to resolve more than 100 mathematical problems. The scoring system is really well done and the discussion forum for each problem is accessible only after having solved the given [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago I&#8217;ve discovered a very interesting and addictive website <a href="http://MathsChallenge.net">MathsChallenge.net</a> . They have a section called <a href="http://www.mathschallenge.net/index.php?section=project">Project Euler</a> where participants can try to resolve more than 100 mathematical problems. The scoring system is really well done and the discussion forum for each problem is accessible only after having solved the given problem.</p>
<p>It&#8217;s interesting to see how other people try to figure out a solution and what languages they employ to solve the puzzling problems. I even discovered rare languages like J or K through this site. <strong>It&#8217;s like a martial arts contest where participants can use their favorite martial art, only this is for hackers.</strong> <img src='http://programmingzen.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>I&#8217;ve only spent a few hours over a couple of days on the site, enough time to solve 26 problems and bring me somewhere around 370th place out of more than 1300 <em>active participants</em> in the contest. I didn&#8217;t spend time solving problems during the last ten days, and in fact I am now 418th. I am going to work on more problems when I&#8217;ll have some time. I love this kind of stuff, and it&#8217;s not just for the enjoyable competition. It doesn&#8217;t really matter if you are first or last, especially if you know how to solve most of the problems but you are short of time like me. What&#8217;s important is to have fun and benefit from the learning process.</p>
<p>The programs must solve the given problems within 60 seconds (think of it like <em>Gone in 60 Seconds</em>), which means that most brute force methods won&#8217;t work.</p>
<p>This is particularly true for Ruby. In fact I have seen some people with C or Assembler resolve a problem with brute force algorithms, where Ruby would take way longer than a minute. There is no harm in this though, it&#8217;s a good exercise in controlling the algorithms&#8217; complexity, facing problems that you don&#8217;t encounter too often in real world programming.</p>
<p>I use Ruby 1.8.4 so I even had to rewrite my own <em>mathn</em> library because prime computation and gcd are exceptionally slow (1.9 solves the problem though).</p>
<p>I invite you to join me and bring up Ruby statistics on MathsChallenge. And above all, have lots of fun&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://programmingzen.com/2006/01/30/solving-mathematical-problems-with-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
