<?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>Stefano Ricciardi &#187; C#</title>
	<atom:link href="http://stefanoricciardi.com/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://stefanoricciardi.com</link>
	<description>On Software Development and Thereabouts</description>
	<lastBuildDate>Tue, 15 Nov 2011 07:57:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Comparing Floating Point Numbers</title>
		<link>http://stefanoricciardi.com/2010/03/02/comparing-floating-point-numbers/</link>
		<comments>http://stefanoricciardi.com/2010/03/02/comparing-floating-point-numbers/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 13:29:00 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.wordpress.com/?p=807</guid>
		<description><![CDATA[Floating Points and Rounding Errors. Working with floating points number can sometimes provide some (un)pleasant surprise, since many real numbers do not have a finite representation and this can lead to rounding errors. If you need to refresh your knowledge (and have some time to spare), you can find a great treatment in the article [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F03%2F02%2Fcomparing-floating-point-numbers%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F03%2F02%2Fcomparing-floating-point-numbers%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<h2>Floating Points and Rounding Errors.</h2>
<p>Working with floating points number can sometimes provide some (un)pleasant surprise, since many real numbers do not have a finite representation and this can lead to rounding errors. </p>
<p>If you need to refresh your knowledge (and have some time to spare), you can find a great treatment in the article <a href="http://docs.sun.com/source/806-3568/ncg_goldberg.html">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a>:</p>
<blockquote><p>
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.
</p></blockquote>
<p>A small example should make the problem clearly visible:</p>
<pre class="brush:csharp">
class Program
{
    static void Main(string[] args)
    {
        double a = 22.4;
        double b = a / 131;

        double c = 0;
        for (int i = 0; i < 131; i++)
        {
            c += b;
        }

        Console.WriteLine("Are they equal?: {0}", a == c);
        Console.WriteLine("Difference (a - c) is {0} ", a - c);
    }
}
</pre>
<p>Here we are taking a double (a), diving it by 131 and then creating a new number (c) by adding the result of that division 131 times. By pure math, a and c should be equal. If you try this small program yourself, this is the output that you would get:</p>
<pre>
Are they equal?: False
Difference (a - c) is -4,9737991503207E-14
</pre>
<p>As you can see, the result is not what you might expect, and it's affected by a rounding error that is building up every time b is added to the partial result c.</p>
<p>Note that this is dependent on the number that I have chosen. If you substitute 131 with 5, you will not experience this problem.</p>
<h2>Your Own Comparer</h2>
<p>Sometimes this behavior might annoy you, especially when you don't need such a high precision and a “rough” equality is all you need. A typical situation is unit testing an algorithm against some expected result: your assertions may fail because of a rounding error, even though the logic of your algorithm is formally correct.</p>
<p>In such a case, you might want to implement your own comparer. A desirable property for such a comparer is a threshold value: if the difference between two floating points is <em>below</em> that threshold they are considered equal.</p>
<p>All you need is to implement the .NET interface <code><a href="http://msdn.microsoft.com/en-us/library/ms132151.aspx">IEqualityComparer</a></code><a href="http://msdn.microsoft.com/en-us/library/ms132151.aspx"> </a>interface.</p>
<pre class="brush:csharp">
class DoubleComparer : IEqualityComparer
{
    private readonly double threshold;

    public DoubleComparer(double threshold)
    {
        this.threshold = threshold;
    }

    public bool Equals(double x, double y)
    {
        return Math.Abs(x - y) < this.threshold;
    }

    public int GetHashCode(double obj)
    {
       return obj.GetHashCode();
    }
}
</pre>
<p>I have created my own comparer to use in my unit tests. I only have to implement 2 methods: <code>Equals()</code> and <code>GetHashCode()</code>.</p>
<p>I don't care much for the actual algorithm of the hashcode implementation, so I am reusing <code>double</code> own algorithm.</p>
<p>Instead, I have applied my own logic to the Equals method: to me, two doubles are equal if the absolute value of their difference is within a given threshold (which I can pass to the comparer in the constructor).</p>
<h2>The Comparer In Use</h2>
<p>Suppose I have an algorithm to calculate the histogram of a given collection of doubles, and a unit test to validate the calculation against a collection of expected results.</p>
<p>In the example below, <em>samples</em> are the input values which I want to create the histogram for, and <em>expectedBreaks</em> is a sequence containing the left and right limits of the bins of the histogram (in the example I am requiring 5 bins, so the number of breaks is 5 + 1 = 6).</p>
<pre class="brush:csharp">
var p = new HistogramProvider();
double[] samples = { 20, 12, 4, 22, 19, 24, 9, 5, -12.2, 13, 0 };
double[] expectedBreaks = { -12.2, -4.96, 2.28, 9.52, 16.76, 24 };

var histogram = p.CreateHistogram(samples, 5);

Assert.IsTrue(expectedBreaks.SequenceEqual<double>(
                       histogram.Breaks,
                       new DoubleComparer(0.01)));
</pre>
<p>I have figured out the threshold to pass (0.01) based on the relative size of the doubles under analysis. Of course, you should use your own judgement to come up with a sensible threshold according of the range of your input data.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f03%2f02%2fcomparing-floating-point-numbers%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f03%2f02%2fcomparing-floating-point-numbers%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Comparing-Floating-Point-Numbers"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F03%2F02%2Fcomparing-floating-point-numbers%2F"></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/03/02/comparing-floating-point-numbers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Generics With Type Uknown At Compile Time</title>
		<link>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/</link>
		<comments>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 20:32:20 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=773</guid>
		<description><![CDATA[The following is an example of a service containing both generic method calls and generic types. public interface IContainer&#60;T&#62; { IEnumerable&#60;IProperty&#60;T&#62;&#62; Properties { get; } } public interface IPropertyService { IContainer&#60;T&#62; GetProperties&#60;T&#62;(string propertyCode); } Now suppose that you don&#8217;t know the actual type of the data until runtime (possibly because the type is retrieved from [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>The following is an example of a service containing both generic method calls and generic types.</p>
<pre class="brush:csharp">
public interface IContainer&lt;T&gt;
{
    IEnumerable&lt;IProperty&lt;T&gt;&gt; Properties { get; }
}

public interface IPropertyService
{
    IContainer&lt;T&gt; GetProperties&lt;T&gt;(string propertyCode);
}
</pre>
<p>Now suppose that you don&#8217;t know the actual type of the data until runtime (possibly because the type is retrieved from a DB or from some other service). You need a way to interact with these generics, and <a href="http://msdn.microsoft.com/en-us/library/system.reflection.aspx">Reflection </a>can help you here.</p>
<p>Let&#8217;s assume that you have managed to get the <code>Type</code> of the data that you are handling (such as <code>string</code>, <code>decimal</code>, <code>double</code>, etc&#8230;) and that you have a concrete implementation of the <code>IPropertyService</code> (perhaps through Dependency Injection).</p>
<p>Once you have that, you can invoke the <code>GetProperty</code> method in the following way:</p>
<pre class="brush:csharp">
Type type = // ... this is the actual runtime type
IPropertyService service = // ... this is an instance of the service

Type serviceType = typeof(IPropertyService);
MethodInfo getPropertiesInfo =
    serviceType.GetMethod(&quot;GetProperties&quot;, new Type[] { typeof(string) });

if (getPropertiesInfo == null)
{
    // Uh-oh.... has the interface changed after we wrote this? Throw an exception...
}

Type[] genericArguments = { type }; // we only have one generic argument (&lt;t&gt;)
MethodInfo getPropertiesMethodInfo =
    getPropertiesInfo.MakeGenericMethod(genericArguments);

// Finally invoke the method to search for a price
var propertiesContainer =
    getPropertiesMethodInfo.Invoke(service, new object[] { &quot;price&quot; });
</pre>
<p>As you can see are quite a few steps to be performed, but at the end, through reflection, you end up with a container filled with all the objects that you have required.</p>
<p>Now assume that you want to access to the single properties contained in the IContainer. You need some way to invoke the C# property <code>Properties</code>. defined on <code>IContainer</code>. Similarly to the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx">MethodInfo</a> class, System.Reflection has a <a href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx">PropertyInfo </a>class that you can use to work with Properties.</p>
<p>The following solution, despite compiling fine, will not work at run-time:</p>
<pre class="brush:csharp">
PropertyInfo containerInfo = typeof(IContainer&lt;&gt;).GetProperty(&quot;Properties&quot;); // WRONG!!!
if (containerInfo == null)
{
    // the interface has changed. Throw an exception
}

var properties = containerInfo.GetValue(container, null) as IEnumerable;
</pre>
<p>If you try to run this, you will be greeted by the following exception: <em>Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.</em></p>
<p>After scratching my head for a while, I realized that I should have first created a generic type at run-time before retrieving the <code>PropertyInfo</code>:</p>
<pre class="brush:csharp">
Type containerType = typeof(IContainer&lt;&gt;).MakeGenericType(type);
PropertyInfo containerInfo = containerType.GetProperty(&quot;Properties&quot;);
if (containerInfo == null)
{
    // the interface has changed. Throw an exception
}

var properties = containerInfo.GetValue(container, null) as IEnumerable;
</pre>
<p>At this point I have a collection of <code>IProperties</code> which I can enumerate through. If needed, since the types in this collection are also generic, I need to repeat the process above until I reach a fundamental type (such as <code>string</code>, <code>double</code>, etc&#8230;).</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f02%2f18%2fgenerics-with-type-uknown-at-compile-time%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f02%2f18%2fgenerics-with-type-uknown-at-compile-time%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/Generics-With-Type-Uknown-At-Compile-Time-Stefano-Ricciardis-Blog"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F02%2F18%2Fgenerics-with-type-uknown-at-compile-time%2F"></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

