RSS

Loop with step increment of 0.1

01 Mar

I didn’t find out the mistake when looping with step increment of 0.1 until I saw the result of the following code:

for (double number = -2; number <= 1; number+=0.1)
    {
        Response.Write(number);
        Response.Write("<br>");
    }


-2
-1.9
-1.8
-1.7
-1.6
-1.5
-1.4
-1.3
-1.2
-1.1
-0.999999999999999
-0.899999999999999
-0.799999999999999
-0.699999999999999
-0.599999999999999
-0.499999999999999
-0.399999999999999
-0.299999999999999
-0.199999999999999
-0.0999999999999994
6.38378239159465E-16
0.100000000000001
0.200000000000001
0.300000000000001
0.400000000000001
0.500000000000001
0.600000000000001
0.700000000000001
0.800000000000001
0.900000000000001

Totally forgot what I learned at school…
We count using decimal numbering system but computer counts using binary numbering system. See more details onĀ INFO: Visual Basic and Arithmetic Precision and the book Computer Organization And Design. I rewrote it to count correctly below:

for (double number = -20; number <= 10; number += 1)
{
    Response.Write(number/10);
    Response.Write("<br>");
}
Advertisements
 
Leave a comment

Posted by on March 1, 2012 in .NET, C#

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: