<?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>Fabulous Adventures In Coding</title>
	<atom:link href="http://ericlippert.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ericlippert.com</link>
	<description>Eric Lippert&#039;s blog</description>
	<lastBuildDate>Tue, 21 May 2013 13:53:37 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Benchmarking mistakes, part two</title>
		<link>http://ericlippert.com/2013/05/21/benchmarking-mistakes-part-two/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=benchmarking-mistakes-part-two</link>
		<comments>http://ericlippert.com/2013/05/21/benchmarking-mistakes-part-two/#comments</comments>
		<pubDate>Tue, 21 May 2013 13:53:37 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[benchmarks]]></category>
		<category><![CDATA[tech.pro]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1167</guid>
		<description><![CDATA[Part two of my Tech.pro beginner-level series on how to write bad benchmarking code can be found here.]]></description>
				<content:encoded><![CDATA[<p>Part two of my <a href="https://tech.pro/">Tech.pro</a> beginner-level series on how to write bad benchmarking code can be found <a href="https://tech.pro/tutorial/1295/c-performance-benchmark-mistakes-part-two">here</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/21/benchmarking-mistakes-part-two/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>What is lexical scoping?</title>
		<link>http://ericlippert.com/2013/05/20/what-is-lexical-scoping/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-is-lexical-scoping</link>
		<comments>http://ericlippert.com/2013/05/20/what-is-lexical-scoping/#comments</comments>
		<pubDate>Mon, 20 May 2013 14:01:13 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1136</guid>
		<description><![CDATA[Happy Eliza Doolittle day all; today seems like an appropriate day for careful elocution of technical jargon. So today, yet another question about "scope". As one of the more over-used jargon terms in programming languages, I get a lot of questions about &#8230; <a href="http://ericlippert.com/2013/05/20/what-is-lexical-scoping/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Happy <a href="http://www.youtube.com/watch?v=pwNKyTktDIE">Eliza Doolittle day</a> all; today seems like an appropriate day for careful elocution of technical jargon. So today, yet another question about "scope". As one of the more over-used jargon terms in programming languages, I get a lot of questions about it.</p>
<p>I'll remind you all again that in C# the term "scope" has a very carefully defined meaning: the <strong>scope</strong> of a named entity is the region of <strong>program text</strong> in which the <strong>unqualified </strong>name can be used to <strong>refer</strong> <strong>to</strong> the entity.<sup class="footnote"><a href="#fn-1136-1" id="fnref-1136-1" onclick="return fdfootnote_show(1136)">1</a></sup></p>
<p><span id="more-1136"></span></p>
<p>For example, the scope of a local variable is the text of the block which declares it. The scope of a private method is the text of the body of the class or struct which declares it. And so on; the C# specification has careful definitions which define the scope of everything that has a name.</p>
<p>The word "lexical" means, in a broad sense "relating to text", and clearly we have defined "scope" as being a relationship involving text, so is this kind of scoping also called "lexical scoping"?</p>
<p>Sort of, but not exactly. Let me explain.</p>
<p>Programming languages can be broadly divided into two categories: the <strong>lexically scoped languages</strong> and the <strong>dynamically scoped languages</strong>. The difference between the two is: in a lexically scoped language, the meaning of an unqualified name can be <strong>completely determined by looking at the program text</strong>; the analysis can be done "statically". In a dynamically scoped language the meaning of an unqualified name can change at runtime; the name analysis can only be done "dynamically".</p>
<p>Let me give you an example; it is easiest to show this with lambdas.</p>
<pre>class C
{
  public static Func&lt;int&gt; M()
  {
    int x = 123;
    return () =&gt; x;
  }
}
class P
{
  static void Main()
  {
    int x = 456;
    Func&lt;int&gt; f = C.M();
    System.Console.WriteLine(f());
  }
}</pre>
<p>The question is: what gets printed out? C# is a lexically scoped language, so the meaning of <code>x</code> in the lambda is determined at compile time, by analyzing the text <i>where the lambda was written</i>. C# prints out <code>123</code>. If C# were a dynamically scoped language then the meaning of <code>x</code> would be determined by analyzing the location <i>where the delegate was executed at runtime</i>, so it would print out <code>456</code>.</p>
<p>Dynamically scoped languages essentially make the C# definition of scope useless; any method that executes a lambda in a dynamically scoped language makes the region of program text in which its locals can be referred to by their names arbitrarily large.</p>
<p>JavaScript, though a very dynamic language, is actually for the most part lexically scoped:</p>
<pre>function M()
{
  var x = 123;
  return function () { return x; };
}
function N()
{
  var x = 456;
  var f = M();
  print(f()); // 123
}</pre>
<p>However, JavaScript does have one feature which makes it dynamically scoped:</p>
<pre>function Q(y)
{
  var x = 123;
  with(y)
    return x;
}
print(Q({ x : 456 })); // 456
print(Q(789));         // 123</pre>
<p>Here the meaning of unqualified name <code>x</code> changes at runtime depending on whether <code>y</code> has a member <code>x</code> or not. For this reason I recommend avoiding the <code>with</code> block in JavaScript; it makes it hard for the reader to understand the meaning of the program.</p>
<p>Most modern languages are lexically scoped; experience has shown that lexical scoping is easier on all concerned; developers and maintenance programmers have an easier time understanding lexically scoped languages, and compiler developers have an easier time writing efficient compilers. Some variants of Lisp use dynamic scoping, though Scheme requires lexical scoping. There are still a few dynamically scoped languages in common usage though; PostScript, the programming language which runs on printers, is perhaps the most commonly used of them.</p>
<div class="footnotes" id="footnotes-1136">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1136-1'>Scope is often confused with the closely related concepts of <strong>declaration space</strong> (the region of code in which no two things may be declared to have the same name), <strong>accessibility domain</strong> (the region of program text in which a member's accessibility modifier permits it to be looked up), and <strong>lifetime</strong> (the portion of the execution of the program during which the contents of a variable are not eligable for garbage collection.) <span class='footnotereverse'><a href='#fnref-1136-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/20/what-is-lexical-scoping/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Quality assurance fail</title>
		<link>http://ericlippert.com/2013/05/17/quality-assurance-fail/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=quality-assurance-fail</link>
		<comments>http://ericlippert.com/2013/05/17/quality-assurance-fail/#comments</comments>
		<pubDate>Fri, 17 May 2013 13:54:21 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[Non-computer]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1141</guid>
		<description><![CDATA[Some fun for Friday. I just opened up a box containing a brand-new bit of telecommunications equipment, and the power supply arrived looking like this, fresh out of the box. (Click for a larger version.) How bad does your quality &#8230; <a href="http://ericlippert.com/2013/05/17/quality-assurance-fail/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://ericlippert.com/wp-content/uploads/2013/05/PowerSupply.jpg"><img class="alignleft size-thumbnail wp-image-1142" alt="PowerSupply" src="http://ericlippert.com/wp-content/uploads/2013/05/PowerSupply-150x150.jpg" width="150" height="150" /></a>Some fun for Friday. I just opened up a box containing a brand-new bit of telecommunications equipment, and the power supply arrived looking like this, fresh out of the box. (Click for a larger version.)</p>
<p>How bad does your quality assurance have to be to ship to customers a power supply that cannot possibly fit into a power socket?</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/17/quality-assurance-fail/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Spot the defect: rounding, part two</title>
		<link>http://ericlippert.com/2013/05/16/spot-the-defect-rounding-part-two/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=spot-the-defect-rounding-part-two</link>
		<comments>http://ericlippert.com/2013/05/16/spot-the-defect-rounding-part-two/#comments</comments>
		<pubDate>Thu, 16 May 2013 13:53:26 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[floating point arithmetic]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1110</guid>
		<description><![CDATA[Last time I challenged you to find a value which does not round correctly using the algorithm Math.Floor(value + 0.5) The value which does not round correctly is the double 0.49999999999999994, which is the largest double that is smaller than &#8230; <a href="http://ericlippert.com/2013/05/16/spot-the-defect-rounding-part-two/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Last time I challenged you to find a value which does not round correctly using the algorithm</p>
<p><code>Math.Floor(value + 0.5)</code></p>
<p>The value which does not round correctly is the double <code>0.49999999999999994</code>, which is the largest double that is smaller than <code>0.5</code>. With the given algorithm this rounds up to <code>1.0</code>, even though clearly <code>0.49999999999999994 </code>is less than one half, and therefore should round down.</p>
<p>What the heck is going on here?</p>
<p><span id="more-1110"></span></p>
<p>As you probably know, doubles are represented internally as binary fractions. The original double in binary<sup class="footnote"><a href="#fn-1110-1" id="fnref-1110-1" onclick="return fdfootnote_show(1110)">1</a></sup> is</p>
<p><code>1.1111111111111111111111111111111111111111111111111111 x 2<sup>-2</sup></code></p>
<p>Or</p>
<p><code>0.011111111111111111111111111111111111111111111111111111</code></p>
<p>which in decimal is</p>
<p><code>0.499999999999999944488848768742172978818416595458984375</code></p>
<p>As you can see it is extremely close to the stated value. Again, just so we are clear: when in source code you say <code>0.49999999999999994</code>, that decimal fraction is rounded to the nearest binary fraction that has no more than 52 bits after the decimal place.</p>
<p>Already we have one rounding, and as you can see, we rounded up -- but we're still less than half.</p>
<p>Now suppose we took this value and added exactly <code>0.5</code> to it. We'd get</p>
<p><code>0.999999999999999944488848768742172978818416595458984375</code></p>
<p>which is still smaller than one. Therefore we'd expect this to go to zero when passed to <code>Math.Floor</code>, right?</p>
<p>Wrong; that fraction isn't a legal double because <strong>it would require 53 bits of precision to represent exactly</strong>. A double only has 52 bits of precision, and therefore this must be rounded off when it becomes a double.</p>
<p>But rounded to what? Clearly it is extremely close to <code>1.0</code>. What is the largest double value that is smaller than <code>1.0</code>? In binary that would be</p>
<p><code>1.1111111111111111111111111111111111111111111111111111 x 2<sup>-1</sup></code></p>
<p>Or</p>
<p><code>0.11111111111111111111111111111111111111111111111111111</code></p>
<p>which is</p>
<p><code>0.99999999999999988897769753748434595763683319091796875</code></p>
<p>in decimal.</p>
<p>So we now have three relevant values:</p>
<pre>0.999999999999999888977697537484345957636833190917968750 (largest double smaller than 1.0)
0.999999999999999944488848768742172978818416595458984375 (exact)
1.000000000000000000000000000000000000000000000000000000 (1.0)</pre>
<p>Which one should we round the middle one to? Well, which is closer?</p>
<p>It's OK, I'll wait while you do the math by hand.</p>
<p>.</p>
<p>.</p>
<p>.</p>
<p><strong>Neither is closer</strong>. The value is exactly in the middle of the two possibilities. The difference is</p>
<p><code>0.000000000000000055511151231257827021181583404541015625</code></p>
<p>in both directions.</p>
<p>Of course you could have worked that out a lot more easily in binary than in decimal! The three numbers are in binary:</p>
<pre>0.111111111111111111111111111111111111111111111111111110
0.111111111111111111111111111111111111111111111111111111
1.000000000000000000000000000000000000000000000000000000</pre>
<p>From which you can read off that difference between both pairs is 2<sup>-54</sup>.</p>
<p>When faced with this situation the floating point chip has got to make a decision and it decides to once again round up; it has no reason to believe that <em>you</em> really want it to round down. So the sum rounds to the double <code>1.0</code>, which is then "floored" to <code>1.0</code>.</p>
<p>Once again we see that <em>floating point math does not behave at all like pen-and-paper math</em>. Just because an algorithm would always work in exact arithmetic does not mean that it always works in inexact floating point. Multiple roundings of extremely small values can add up to a large difference.</p>
<p>I've posted the code I used to make all these calculations below; long-time readers will recognize it from my <a href="http://blogs.msdn.com/b/ericlippert/archive/2011/02/17/looking-inside-a-double.aspx">previous article on how to decompose a double into its constituent parts</a>.</p>
<hr />
<pre>using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SolverFoundation.Common;

class Program
{
    static void Main()
    {
        MyDouble closeToHalf_Double = 0.49999999999999994;
        Rational closeToHalf_Rational = DoubleToRational(closeToHalf_Double);

        Console.WriteLine("0.49999999999999994");
        Console.WriteLine("Actual value of double in binary:");
        Console.WriteLine("1.{0} x 2 to the {1}", 
            closeToHalf_Double.MantissaBits.Join(), 
            closeToHalf_Double.Exponent - 1023);
        Console.WriteLine("Actual value of double as fraction:");
        Console.WriteLine(closeToHalf_Rational.ToString());
        Console.WriteLine("Actual value of double in decimal:");
        Console.WriteLine(closeToHalf_Rational.ToDecimalString());
        Console.WriteLine();

        MyDouble closeToOne_Double = 0.99999999999999994;
        Rational closeToOne_Rational = DoubleToRational(closeToOne_Double);

        Console.WriteLine("0.99999999999999994");
        Console.WriteLine("Actual value of double in binary:");
        Console.WriteLine("1.{0} x 2 to the {1}",
            closeToOne_Double.MantissaBits.Join(),
            closeToOne_Double.Exponent - 1023);
        Console.WriteLine("Actual value of double as fraction:");
        Console.WriteLine(closeToOne_Rational.ToString());
        Console.WriteLine("Actual value of double in decimal:");
        Console.WriteLine(closeToOne_Rational.ToDecimalString());
        Console.WriteLine();

        // Now let's do the arithmetic in "infinite precision":

        Rational sum = closeToHalf_Rational + (Rational)0.5;

        Console.WriteLine("Sum in exact arithmetic as fraction:");
        Console.WriteLine(closeToOne_Rational.ToString());
        Console.WriteLine("Sum in exact arithmetic in decimal:");
        Console.WriteLine(closeToOne_Rational.ToDecimalString());

        // But that has more precision than will fit into a double, 
        // so we have to round off. We have two possible values:

        Rational d1 = Rational.One - sum;
        Rational d2 = sum - closeToOne_Rational;

        Console.WriteLine("Difference from one:");
        Console.WriteLine(d1.ToDecimalString());
        Console.WriteLine("Difference from closeToOne:");
        Console.WriteLine(d2.ToDecimalString());
    }

    static Rational DoubleToRational(MyDouble d)
    {
        bool subnormal = d.Exponent == 0;
        var two = (Rational)2;
        var fraction = subnormal ? Rational.Zero : Rational.One;
        var adjust = subnormal ? 1 : 0;
        for (int bit = 51; bit &gt;= 0; --bit)
            fraction += d.Mantissa.Bit(bit) * two.Exp(bit - 52 + adjust);
        fraction = fraction * two.Exp(d.Exponent - 1023);
        if (d.Sign == 1)
            fraction = -fraction;
        return fraction;
    }
}

struct MyDouble
{
    private ulong bits;
    public MyDouble(double d)
    {
        this.bits = (ulong)BitConverter.DoubleToInt64Bits(d);
    }

    public int Sign
    {
        get
        {
            return this.bits.Bit(63);
        }
    }

    public int Exponent
    {
        get
        {
            return (int)this.bits.Bits(62, 52);
        }
    }

    public IEnumerable&lt;int&gt; ExponentBits
    {
        get
        {
            return this.bits.BitSeq(62, 52);
        }
    }

    public ulong Mantissa
    {
        get
        {
            return this.bits.Bits(51, 0);
        }
    }

    public IEnumerable MantissaBits
    {
        get
        {
            return this.bits.BitSeq(51, 0);
        }
    }

    public static implicit operator MyDouble(double d)
    {
        return new MyDouble(d);
    }
}

static class Extensions
{
    public static int Bit(this ulong x, int bit)
    {
        return (int)((x &gt;&gt; bit) &amp; 0x01);
    }

    public static ulong Bits(this ulong x, int high, int low)
    {
        x &lt;&lt;= (63 - high);
        x &gt;&gt;= (low + 63 - high);
        return x;
    }

    public static IEnumerable&lt;int&gt; BitSeq(this ulong x, int high, int low)
    {
        for (int bit = high; bit &gt;= low; --bit)
            yield return x.Bit(bit);
    }

    public static Rational Exp(this Rational x, int y)
    {
        Rational result;
        Rational.Power(x, y, out result);
        return result;
    }

    public static string ToDecimalString(this Rational x)
    {
        var sb = new StringBuilder();
        x.AppendDecimalString(sb, 50000);
        return sb.ToString();
    }

    public static string Join&lt;T&gt;(this IEnumerable seq)
    {
        return string.Concat(seq);
    }
}</pre>
<div class="footnotes" id="footnotes-1110">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1110-1'>Obviously the mantissa is in binary and the exponent is in decimal. <span class='footnotereverse'><a href='#fnref-1110-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/16/spot-the-defect-rounding-part-two/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Benchmarking mistakes, part one</title>
		<link>http://ericlippert.com/2013/05/14/benchmarking-mistakes-part-one/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=benchmarking-mistakes-part-one</link>
		<comments>http://ericlippert.com/2013/05/14/benchmarking-mistakes-part-one/#comments</comments>
		<pubDate>Tue, 14 May 2013 13:46:57 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[benchmarks]]></category>
		<category><![CDATA[tech.pro]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1129</guid>
		<description><![CDATA[The good people over at Tech.Pro have asked me to write a short series of articles for their site on the subject of mistakes I've made and seen others make when writing benchmark performance tests of C# code. The series &#8230; <a href="http://ericlippert.com/2013/05/14/benchmarking-mistakes-part-one/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The good people over at <a href="http://tech.pro/">Tech.Pro </a>have asked me to write a short series of articles for their site on the subject of mistakes I've made and seen others make when writing benchmark performance tests of C# code. The series will be pitched at the beginner level.</p>
<p>You can check out part one <a href="http://tech.pro/blog/1293/c-performance-benchmark-mistakes-part-one">here</a>. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/14/benchmarking-mistakes-part-one/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Spot the defect: rounding</title>
		<link>http://ericlippert.com/2013/05/13/spot-the-defect-rounding/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=spot-the-defect-rounding</link>
		<comments>http://ericlippert.com/2013/05/13/spot-the-defect-rounding/#comments</comments>
		<pubDate>Mon, 13 May 2013 14:20:10 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[floating point arithmetic]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1104</guid>
		<description><![CDATA[The intention of this method is to round a double to the nearest integer. If the double is exactly half way between two integers then it rounds to the larger of the two possibilities:1 static double MyRound(double d) { return &#8230; <a href="http://ericlippert.com/2013/05/13/spot-the-defect-rounding/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The intention of this method is to round a double to the nearest integer. If the double is exactly half way between two integers then it rounds to the larger of the two possibilities:<sup class="footnote"><a href="#fn-1104-1" id="fnref-1104-1" onclick="return fdfootnote_show(1104)">1</a></sup></p>
<pre>static double MyRound(double d)
{
  return Math.Floor(d + 0.5);
}</pre>
<p>Is it correct? Can you find a value for which it does not give the mathematically correct value?<sup class="footnote"><a href="#fn-1104-2" id="fnref-1104-2" onclick="return fdfootnote_show(1104)">2</a></sup></p>
<p>UPDATE: The answer is in the comments, so if you don't want spoilers, don't read the comments.</p>
<p><strong>Next time on FAIC:</strong> The answer, of course.</p>
<div class="footnotes" id="footnotes-1104">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1104-1'>For negative numbers, -1.5 should round to -1.0, since -1.0 is larger than -2.0; I do not mean larger in the sense of absolute magnitude. That would be characterized as "midpoint rounding away from zero". <span class='footnotereverse'><a href='#fnref-1104-1'>&#8617;</a></span></li>
<li id='fn-1104-2'>HINT: The value I'm thinking of is small. <span class='footnotereverse'><a href='#fnref-1104-2'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/13/spot-the-defect-rounding/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Rerun: I have a mysterious fifth sense</title>
		<link>http://ericlippert.com/2013/05/10/i-have-a-mysterious-fifth-sense/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=i-have-a-mysterious-fifth-sense</link>
		<comments>http://ericlippert.com/2013/05/10/i-have-a-mysterious-fifth-sense/#comments</comments>
		<pubDate>Fri, 10 May 2013 15:17:26 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[Non-computer]]></category>
		<category><![CDATA[recruiting]]></category>
		<category><![CDATA[rerun]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1099</guid>
		<description><![CDATA[Today, another of my ongoing series of reruns of my fun-for-Friday non-computer posts. Here's one from the dot-com recovery of 2004. The economy must be picking up -- I'm getting cold calls from recruiters again for the first time in &#8230; <a href="http://ericlippert.com/2013/05/10/i-have-a-mysterious-fifth-sense/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Today, another of my ongoing series of reruns of my fun-for-Friday non-computer posts. Here's one from the dot-com recovery of 2004.</p>
<hr/>
The economy must be picking up -- I'm getting cold calls from recruiters again for the first time in about four years.  Today was the second - and third - this month.</p>
<p>However, apparently some of them are just a wee bit disorganized. I just had the following conversations:</p>
<p>[Ring ring]</p>
<p><strong>Me</strong>: Hi, this is Eric.</p>
<p><strong>Her</strong>: Hi, this is Barbara<sup class="footnote"><a href="#fn-1099-1" id="fnref-1099-1" onclick="return fdfootnote_show(1099)">1</a></sup> at XYZ Recruiters. How are you today?</p>
<p><span id="more-1099"></span></p>
<p><strong>Me</strong>: I am <strong>extremely</strong> well! How are you feeling today, Barbara?</p>
<p>[This seemed to <i>completely</i> flummox Barbara. Perhaps people who are interrupted at work by cold callers do not usually inquire as to her health?]</p>
<p><strong>Her</strong>: Uh. Um. Me? Uh, I'm fine I guess! Thanks for asking!</p>
<p>[Brief pause -- OK, I guess keeping this conversation going is up to me.]</p>
<p><strong>Me</strong>: So what's up, Barbara?</p>
<p><strong>Her, back to the script</strong>: There's a small company in downtown Seattle that is 60% ex-Microsoft people and they're looking to hire C++ devs. They've just landed a big contract with Foo corp.</p>
<p><strong>Me</strong>: Well thanks for thinking of me Barbara. I'm happy to speak with you but to be fair I first must warn you that I am <strong>intensely loyal</strong>.</p>
<p><strong>Her</strong>: Oh. Well, thanks for your time. Bye.</p>
<p><strong>Me</strong>: Bye!</p>
<p>Wow, she didn't put up a fight <i>at all</i>. Maybe the economy isn't picking up so much. Four years ago recruiters - who were for some reason invariably female - would flirt with me and then try to get me interested in crappy database admin jobs in the Cayman Islands, of all places.</p>
<p>Ah well, back to work. I resolve an old bug that got fixed a while back but was never updated in the bug database. I start looking at another bug and researching the history of a particular code change. We've made a minor change to the formatting of an XML file and Mario wants to know whether that was by design or an accident, when...</p>
<p>[Ring Ring -- hey, the caller id looks familiar...]</p>
<p><strong>Me</strong>: Hi, this is Eric.</p>
<p><strong>Her</strong>: Hi this is...</p>
<p><strong>Me</strong>: Barbara at XYZ recruiters?</p>
<p><strong>Her</strong>: Uh, yes. How...</p>
<p><strong>Me</strong>: What's new?</p>
<p>[Like Hobbes, I love <a href="http://tvtropes.org/pmwiki/pmwiki.php/Main/OhCrap">the moment of dawning comprehension</a>. Barbara hits it.]</p>
<p><strong>Her</strong>: Wait... did I call you already?</p>
<p><strong>Me</strong>: Yes, about ten minutes ago.</p>
<p><strong>Her, trying to place me</strong>: Uh… are you a C++ developer?</p>
<p><strong>Me</strong>: Why yes I am as a matter of fact!</p>
<p><strong>Her, paging in at last</strong>: You're the one who's "intensely loyal", right?</p>
<p><strong>Me</strong>: Indeed. And I still am. Cold-calling recruiting really is kind of about looking for <i>disloyal</i> people, isn't it? People who will just pick up when something better comes along, right?</p>
<p><strong>Her</strong>: Hey, some people are looking for a change! Wanting change in your life doesn't make you disloyal, does it?</p>
<p><strong>Me</strong>: Well, you're the expert. I'll take your word for it.<sup class="footnote"><a href="#fn-1099-2" id="fnref-1099-2" onclick="return fdfootnote_show(1099)">2</a></sup></p>
<p>This brought back fond memories of my teenage days. Unlike my crazy friends, I never prank <em><b>called</b> </em>people, but I prank <em><b>answered</b> </em>them all the time.<sup class="footnote"><a href="#fn-1099-3" id="fnref-1099-3" onclick="return fdfootnote_show(1099)">3</a></sup> Having two voice lines in the house (one for my 300 baud modem on the Commodore 64, of course) led to ample opportunities for consecutive calls from clueless telemarketers. On the second call I'd just answer with "<em>Don't say anything! I have a mysterious <a href="http://www.script-o-rama.com/movie_scripts/l/la-story-script-transcript-martin.html">fifth sense</a>! My psychic powers tell me that your name is Helen, and you want to sell me... magazine subscriptions! Yes?" </em></p>
<p>Freaked them out every time.</p>
<div class="footnotes" id="footnotes-1099">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1099-1'>I learned later from some of my fellow Microsoftie bloggers that it appeared that Barbara was calling everyone at Microsoft with an MSDN blog. She must have been repeatedly calling the switchboard and asking to speak with each. <span class='footnotereverse'><a href='#fnref-1099-1'>&#8617;</a></span></li>
<li id='fn-1099-2'>Barbara was right and I was wrong. I am still loyal to Microsoft, and yet I needed to make a change. Thanks Barbara! <span class='footnotereverse'><a href='#fnref-1099-2'>&#8617;</a></span></li>
<li id='fn-1099-3'>You phone me, you take that risk. The moral: send email. <span class='footnotereverse'><a href='#fnref-1099-3'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/10/i-have-a-mysterious-fifth-sense/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Producing permutations, part seven</title>
		<link>http://ericlippert.com/2013/05/06/producing-permutations-part-seven/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=producing-permutations-part-seven</link>
		<comments>http://ericlippert.com/2013/05/06/producing-permutations-part-seven/#comments</comments>
		<pubDate>Mon, 06 May 2013 14:15:05 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[permutations]]></category>
		<category><![CDATA[randomness]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1043</guid>
		<description><![CDATA[Last time on FAIC I generated a "random" permutation of a deck of cards and gave you the first five cards, and challenged you to determine what the next five cards were. David Poeschl1 was the first to get a possible &#8230; <a href="http://ericlippert.com/2013/05/06/producing-permutations-part-seven/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://ericlippert.com/2013/05/02/producing-permutations-part-six/" title="Producing permutations, part six">Last time on FAIC </a>I generated a "random" permutation of a deck of cards and gave you the first five cards, and challenged you to determine what the next five cards were. David Poeschl<sup class="footnote"><a href="#fn-1043-1" id="fnref-1043-1" onclick="return fdfootnote_show(1043)">1</a></sup> was the first to get a <em>possible</em> order and, with the additional hint that the sixth card was the three of hearts, Joel Rondeau found the correct solution, which is below. Both used brute-force algorithms.</p>
<p><span id="more-1043"></span></p>
<p>The problem with my algorithm, as David points out in the comments, is that there are 52! possible orderings of a deck, which is approximately 2<sup>226</sup>, but there are only 2<sup>32</sup> possible "seeds" to the pseudo-random number generate that is <code>Math.Random</code>, and therefore only a tiny fraction of the decks can possibly be generated. In fact, the situation is far worse than that; when no seed is given, the class defaults to using the absolute value of <code>Environment.TickCount</code> which measures the number of milliseconds since the machine was turned on. However, this value is only updated approximately 60 times a second. The upshot of this is:</p>
<ul>
<li>Because the absolute value is taken, the actual seed is only drawn from 2<sup>31</sup> possible values.</li>
<li>Since a lot of people boot their machines when they need them rather than keeping them on all the time, the seed is typically much less than the number of milliseconds in a day.</li>
<li>If Random is seeded twice and you manage to work out one of the seeds, you might be able to cut down the problem of figuring out the other by a factor of 60 or so -- not that it matters; as we've seen, brute-forcing is fast.</li>
</ul>
<p>There are 52 x 51 x 50 x 49 x 48 = about 2<sup>28</sup> possible first five cards of a deck, and 2<sup>31</sup> possible seeds. That means that on average there will be only 2<sup>3</sup> decks that can possibly be generated by this algorithm that start with those five cards, out of the actual 2<sup>197</sup> decks that could start with those five cards! And when given a sixth card, it is almost always going to be possible to find the unique deck that can be generated using this algorithm.</p>
<p>If you're going to be shuffling a deck of cards by choosing a random permutation and there is a need for actual unpredictability then you should <strong>use a random or pseudo-random number generator that has at least 226 bits of "entropy" in the seed</strong>. The <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator.aspx"><code>RandomNumberGenerator</code></a> class is suitable for this purpose, <code>Math.Random</code> is not.</p>
<p><strong>Next time on FAIC</strong>: I've been asked to write a series of articles for another site and they'll take me a bit to work out, so I'll probably skip the next couple of episodes of FAIC. More bulletins as events warrant.</p>
<hr />
<pre>39: Ace of Clubs
11: Queen of Spades
29: Four of Diamonds
5: Six of Spades
20: Eight of Hearts
15: Trey of Hearts
3: Four of Spades
16: Four of Hearts
33: Eight of Diamonds
43: Five of Clubs
49: Jack of Clubs
1: Deuce of Spades
22: Ten of Hearts
27: Deuce of Diamonds
25: King of Hearts
2: Trey of Spades
44: Six of Clubs
6: Seven of Spades
21: Nine of Hearts
17: Five of Hearts
35: Ten of Diamonds
12: King of Spades
48: Ten of Clubs
4: Five of Spades
41: Trey of Clubs
42: Four of Clubs
51: King of Clubs
36: Jack of Diamonds
7: Eight of Spades
28: Trey of Diamonds
18: Six of Hearts
0: Ace of Spades
13: Ace of Hearts
14: Deuce of Hearts
10: Jack of Spades
9: Ten of Spades
24: Queen of Hearts
50: Queen of Clubs
19: Seven of Hearts
47: Nine of Clubs
37: Queen of Diamonds
34: Nine of Diamonds
40: Deuce of Clubs
45: Seven of Clubs
23: Jack of Hearts
31: Six of Diamonds
32: Seven of Diamonds
30: Five of Diamonds
46: Eight of Clubs
8: Nine of Spades
38: King of Diamonds
26: Ace of Diamonds</pre>
<div class="footnotes" id="footnotes-1043">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1043-1'>Of the Roslyn team! <span class='footnotereverse'><a href='#fnref-1043-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/06/producing-permutations-part-seven/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Producing permutations, part six</title>
		<link>http://ericlippert.com/2013/05/02/producing-permutations-part-six/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=producing-permutations-part-six</link>
		<comments>http://ericlippert.com/2013/05/02/producing-permutations-part-six/#comments</comments>
		<pubDate>Thu, 02 May 2013 13:31:11 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[permutations]]></category>
		<category><![CDATA[randomness]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1038</guid>
		<description><![CDATA[Last time in this series I presented an algorithm for generating a random number, and the time before I presented an algorithm that turns such a number into a permutation, so we can put them together to make an algorithm that &#8230; <a href="http://ericlippert.com/2013/05/02/producing-permutations-part-six/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a title="Producing permutations, part five" href="http://ericlippert.com/2013/04/29/producing-permutations-part-five/">Last time in this series</a> I presented an algorithm for generating a random number, and the time before I presented an algorithm that turns such a number into a permutation, so we can put them together to make an algorithm that returns a random permutation:</p>
<pre>static Permutation RandomPermutation(int size, Random random)
{
  return Permutation.NthPermutation(size, RandomFactoradic(size, random));
}</pre>
<p>Is this actually a correct algorithm for generating a random permutation? Give it some thought.</p>
<p><span id="more-1038"></span></p>
<p>Turns out, surprisingly, no, it is not correct. Now, there's no flaw that I'm aware of in the logic or the mathematics that underlies it. Rather, the problem is that the <code>Random</code> type is a big fat lie. We'd like to have the property that a random permutation generator produces every possible permutation with equal likelihood; that is, it should be unbiased. This algorithm is deeply biased because <code>Random</code> is not a strong enough source of random numbers. <strong>Some permutations are less likely than others.</strong></p>
<p>So what's the big deal? If there were just a small bias, that would be unfortunate but not fatal. It's actually worse than that. With this bad source of randomness, <strong>given a portion of a permutation, you can work out what the rest of the permutation likely is.</strong></p>
<p>And that's my challenge to you. I've posted some code below, putting together everything we've seen so far in this series. The first five card dealt when I ran the program were:</p>
<pre>39: Ace of Clubs
11: Queen of Spades
29: Four of Diamonds
5: Six of Spades
20: Eight of Hearts</pre>
<p>My challenge to you is: what are the next five cards that I generated? And.... go!</p>
<pre>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

public static class Extensions
{
    public static IEnumerable&lt;T&gt; InsertAt&lt;T&gt;(
      this IEnumerable&lt;T&gt; items, int position, T newItem)
    {
        if (items == null)
            throw new ArgumentNullException("items");
        if (position &lt; 0)
            throw new ArgumentOutOfRangeException("position");
        return InsertAtIterator&lt;T&gt;(items, position, newItem);
    }

    private static IEnumerable&lt;T&gt; InsertAtIterator&lt;T&gt;(
        this IEnumerable&lt;T&gt; items, int position, T newItem)
    {
        int index = 0;
        bool yieldedNew = false;
        foreach (T item in items)
        {
            if (index == position)
            {
                yield return newItem;
                yieldedNew = true;
            }
            yield return item;
            index += 1;
        }
        if (index == position)
        {
            yield return newItem;
            yieldedNew = true;
        }
        if (!yieldedNew)
            throw new ArgumentOutOfRangeException("position");
    }
}

struct Permutation : IEnumerable&lt;int&gt;
{
    public static Permutation Empty { get { return empty; } }
    private static Permutation empty = new Permutation(new int[] { });
    private int[] permutation;
    private Permutation(int[] permutation)
    {
      this.permutation = permutation;
    }

    private Permutation(IEnumerable&lt;int&gt; permutation) 
      : this(permutation.ToArray()) { }

    private static BigInteger Factorial(int x)
    {
      BigInteger result = 1;
      for (int i = 2 ; i &lt;= x ; ++i)
        result *= i;
      return result;       
    }

    public static Permutation NthPermutation(int size, BigInteger index)
    {
      if (index &lt; 0 || index &gt;= Factorial(size))
        throw new ArgumentOutOfRangeException("index");
      if (size == 0)
        return Empty;
      BigInteger group = index / size;
      bool forwards = group % 2 != 0;
      Permutation permutation = NthPermutation(size - 1, group);
      int i = (int) (index % size);                      
      return new Permutation(
        permutation.InsertAt(forwards ? i : size - i - 1, size - 1));
    }

    // Produce a random number between 0 and n!-1
    static BigInteger RandomFactoradic(int n, Random random)
    {
      BigInteger result = 0;
      BigInteger radix = 1;
      for (int i = 1; i &lt; n; ++i)
      {
        // We need a digit between 0 and i.
        result += radix * random.Next(i+1);
        radix *= (i+1);
      }
      return result;
    }
    public static Permutation RandomPermutation(int size, Random random)
    {
      return NthPermutation(size, RandomFactoradic(size, random));
    }
    public int this[int index]
    {
      get { return permutation[index]; }
    }
    public IEnumerator&lt;int&gt; GetEnumerator()
    {
      foreach (int item in permutation)
        yield return item;
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      return this.GetEnumerator();
    }
    public int Count { get { return this.permutation.Length; } }
    public override string ToString()
    {
      return string.Join&lt;int&gt;(",", permutation);
    }
}

class Program
{
    static void Main()
    {
        string[] suits = { "Spades", "Hearts", "Diamonds", "Clubs" };
        string[] values = {"Ace", "Deuce", "Trey", "Four", "Five",
                       "Six", "Seven", "Eight", "Nine", "Ten",
                       "Jack", "Queen", "King" };
        Permutation p = Permutation.RandomPermutation(52, new Random());
        foreach (int i in p)
            Console.WriteLine("{0}: {1} of {2}", 
                i, values[i % 13], suits[i / 13]);
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/02/producing-permutations-part-six/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Mmm, curry</title>
		<link>http://ericlippert.com/2013/05/01/mmm-curry/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mmm-curry</link>
		<comments>http://ericlippert.com/2013/05/01/mmm-curry/#comments</comments>
		<pubDate>Wed, 01 May 2013 14:27:25 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1077</guid>
		<description><![CDATA[I'm back from a short but productive trip to beautiful San Francisco only to discover that the May-June issue of Dot Net Curry magazine in my inbox apparently has me on the cover. 1 It's free, it's online, but you &#8230; <a href="http://ericlippert.com/2013/05/01/mmm-curry/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.dotnetcurry.com/magazine/dnc-magazine-issue6.aspx"><img class="alignleft size-thumbnail wp-image-1078" alt="dnc-may" src="http://ericlippert.com/wp-content/uploads/2013/05/dnc-may-150x150.png" width="150" height="150" /></a>I'm back from a short but productive trip to beautiful San Francisco only to discover that the <a href="http://www.dotnetcurry.com/magazine/dnc-magazine-issue6.aspx">May-June issue of Dot Net Curry magazine </a>in my inbox apparently has me on the cover. <sup class="footnote"><a href="#fn-1077-1" id="fnref-1077-1" onclick="return fdfootnote_show(1077)">1</a></sup></p>
<p>It's free, it's online, but you have to "<a href="http://www.dotnetcurry.com/magazine/">subscribe</a>" to read it. Check it out!</p>
<hr/>
<p><strong>Next time on FAIC:</strong> More on random permutations.</p>
<hr/>
<p>Photo by my colleague Bob.</p>
<div class="footnotes" id="footnotes-1077">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1077-1'>Fortunately I did know about it ahead of time. <span class='footnotereverse'><a href='#fnref-1077-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/01/mmm-curry/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
