<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/stylesheets/rss.css" type="text/css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Tom Moertel's Weblog: The oddities of floating-point arithmetic</title>
    <link>http://blog.moertel.com/articles/2005/09/27/the-oddities-of-floating-point-arithmetic</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Quality rants on programming theory and stuff geeks like</description>
    <item>
      <title>The oddities of floating-point arithmetic</title>
      <description>&lt;p&gt;Tobias at &lt;a href="http://blog.leetsoft.com/"&gt;too-biased&lt;/a&gt; asks &lt;a href="http://blog.leetsoft.com/articles/2005/09/27/wtf"&gt;wtf?&lt;/a&gt; is going on with the following unintuitive result from Ruby:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;irb(main):001:0&amp;gt; (4.10 * 100).to_i
=&amp;gt; 409
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;What&amp;#8217;s going on is that &lt;em&gt;to_i&lt;/em&gt; truncates its floating-point argument, discarding the fractional part.  The fractional part, owing to the intricacies of floating-point arithmetic, does not agree with our intuition:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;irb(main):002:0&amp;gt; "%3.20g" % (4.10 * 100)
=&amp;gt; "409.99999999999994316" 
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;In this case, the factional part is almost 1. Throwing it away turns our expected result of 410 into the unexpected 409.  (That&amp;#8217;s why &lt;em&gt;round&lt;/em&gt; makes for a better choice than &lt;em&gt;to_i&lt;/em&gt; when we want the nearest integer to our float.)&lt;/p&gt;


	&lt;p&gt;If this behavior seems bizarre, I recommend David Goldberg&amp;#8217;s classic &lt;a href="http://citeseer.ist.psu.edu/goldberg91what.html"&gt;What Every Computer Scientist Should Know About Floating Point Arithmetic (1991)&lt;/a&gt;.  The paper was originally published in &lt;em&gt;&lt;span class="caps"&gt;ACM&lt;/span&gt; Computing Surveys&lt;/em&gt; and later republished with corrections.  The corrected versions, however, were apparently typeset in Microsoft Word, and the formulas are hard to look at (especially if you are accustomed to TeX-quality math typesetting). You might want to get your hands on a &lt;a href="http://cch.loria.fr/documentation/IEEE754/ACM/goldberg.pdf"&gt;&lt;span class="caps"&gt;PDF&lt;/span&gt; of the original version&lt;/a&gt; if you care about that kind of thing.&lt;/p&gt;</description>
      <pubDate>Tue, 27 Sep 2005 22:59:00 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:000efed7699cc61519400c660ada820a</guid>
      <author>Tom Moertel</author>
      <link>http://blog.moertel.com/articles/2005/09/27/the-oddities-of-floating-point-arithmetic</link>
      <category>programming</category>
      <trackback:ping>http://blog.moertel.com/articles/trackback/7</trackback:ping>
    </item>
  </channel>
</rss>
