Freigeben über


Partial Answer: "Double Trouble"

I am so sorry for not posting the answer to "Double Trouble" sonner. Vacation and busy work schedule has prevented me from doing so, but that's no excuse!

Before I dive it why this won't work, I have to admit, you can't really tell without compiling the program. Again, not the best written quiz,:( .... maybe I should just stop making them... but it's a fun way to discuss interesting things in the .NET Framework. What do you think?

One of the main concepts I want to highlight in that post is what Tommy (who was the first person) who posted back to my comments said:

Tuesday, May 09, 2006 2:23 AM by Tommy Carlier

No, I can't. But I have a feeling that it will say 'false' for all 4 the cases. I know that doubles and == don't like each other very much.

 

Double by definition is inexact, and doing equality comparison on it is bad news. Yes, most of the time it'll work, but as I have highlighted here. There are some random numbers where it just won't work!

 

To understand why this is happening try running dumping each of the string to a byte array like this:

 

byte[] dIncorrect = BitConverter.GetBytes(d);

byte[] dCorrect = BitConverter.GetBytes(4.170404);

You will see that the least significant bit is incorrect:

 

dIncorrect {Dimensions:[0x00000008]}
[0x00000000] 0x2a byte
[0x00000001] 0x6e byte
[0x00000002] 0xdc byte
[0x00000003] 0x62 byte
[0x00000004] 0x7e byte
[0x00000005] 0xae byte
[0x00000006] 0x10 byte
[0x00000007] 0x40 byte
dCorrect {Dimensions:[0x00000008]}
[0x00000000] 0x2b byte
[0x00000001] 0x6e byte
[0x00000002] 0xdc byte
[0x00000003] 0x62 byte
[0x00000004] 0x7e byte
[0x00000005] 0xae byte
[0x00000006] 0x10 byte
[0x00000007] 0x40 byte

The next step to the investigation is to see why the bit was parsed incorrectly, which also leads me to my real reason why I haven't posted this earlier. I want to debug down on our code to see what are the "gotcha" numbers that will cause this to be inexact. I still haven't found the time to do it yet... so I will have to post a follow up to the answer.

Comments

  • Anonymous
    July 31, 2006
    >> maybe I should just stop making them...

    Don't you dare stop making them ;-)

    >> but it's a fun way to discuss interesting things in the .NET Framework. What do you think?

    I think you are correct I have always enjoyed your articles as they bring up some odd and wierd behavior I never really spent a lot of time thinking about.
  • Anonymous
    August 08, 2006
    Double will store the number as binary
    so if the decimal was translated to binary without "round-up" errors then the condition is true

    but it is depends on the numbers we are representing
    so some numbers will give true, and others will give false

    to get a real representation of the decimal system, you should instead use Decimal

    Decimal will store the number internally as decimal represetation, and that is why it is very accurate
    But Decimal is slow