The Mystery of Flunf

posted by Craig Gidney on May 14, 2013

This week, I have manufactured a mystery.

Returning readers might see the issue right away. Don’t worry, it’s got nothing to do with unicode.


Why the flunf does the following C# code print ‘False’?

var flunf = 98765432f;

var sortedList = new List<double> {
    flunf + 1, 
    flunf + 3, 
var valueToInsert = flunf + 2;
var indexOfInsert = sortedList.TakeWhile(e => e < flunf + 2).Count();
sortedList.Insert(indexOfInsert, valueToInsert);

var stayedSorted = sortedList.SequenceEqual(sortedList.OrderBy(e => e));
Console.WriteLine(stayedSorted); // prints 'False'

(You should check your solution against the ‘likely mistake’ entry below.)


Hint: The fact that flunf is a float matters, but how it matters is the real puzzle.

Hint: sortedList is [98765433, 98765432, 98765435] in the end.

Hint: The type of float+int is float.

Spoiler: The preceeding hint is correct, but very misleading.

Likely Mistake: If limited precision was the only issue, everything would round to flunf and be trivially sorted.

Disclaimer: It is possible that, in the future or on other machines, the list will actually end up sorted and ‘True’ will be printed. In that case, the puzzle is why and under what conditions could the list end up not sorted? I assure you that the code prints ‘False’ on my machine.

Discuss on Reddit

Comments are closed.

Twisted Oak Studios offers consulting and development on high-tech interactive projects. Check out our portfolio, or Give us a shout if you have anything you think some really rad engineers should help you with.


More interesting posts (15 of 25 articles)

Or check out our Portfolio.