Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have some code and I want to verify that it works for all doubles. Since I am not the trusting sort I would like to have it run through all the doubles and test if my method works. I'm converting the double to another datatype and then converting it back.

Unfortunately this is not a trivial task like going through Int32. If anyone has done this or knows where some code is that does this please let me know.


Thanks
Ken
Posted

All you have to do is test with three or so values. Best case, worst case, and a couple of randomly chosen middle-of-the-road values.

Besides, when you say enumerate through all the doubles, do you mean every possible value? That test will take quite a while to run.
 
Share this answer
 
Comments
KenJohnson 10-Jun-10 13:44pm    
Thanks for responding. I am converting the doubles to a significantly more fine grained numeric type. I want to make sure that one can do a round trip with no loss of information so I would like to test every one. I am aware that the running time of the test may be considerable, but I have an extra computer that I would be willing to let churn for as weeks if necessary.
#realJSOP 10-Jun-10 14:29pm    
If you want accuracy, you should use decimal instead of double. decimal values take a bit longer to work with, but if accuracy is your goal, that's the way to go. With doubles, the minute you do math on them, you can't be entirely sure of what the result will be (1.0 x 1 may result in 1.00000000001).
I'd recommend incrementing a long and then converting it to a double, using the below code:

C#
double dbl;
 
for (long lng = long.MinValue; lng < long.MaxValue; ++lng)
{
    dbl = BitConverter.Int64BitsToDouble(lng);
 
    /* Test the double here */
}
 
// Also test for long.MaxValue as well.
dbl = BitConverter.Int64BitsToDouble(long.MaxValue);

It'll keep you from potentially underflowing if you were to just take a double and increment it by some number.

Be aware, you'll get some special 'case' values from doing this, like infinity and NaN and such. You'll probably want to use the static methods on double to remove those cases or just constrain the value between Min/Max. Something like that...

Have fun with your ~18,446,744,073,709,551,616 test cases. :D
 
Share this answer
 
Comments
KenJohnson 10-Jun-10 18:38pm    
Thanks it is running now. The idea was an excellent one. Incrementing does not work as doubles are not evenly distributed. This working depends on long fully utilizing the entirety of the possible 64 bits available to it and double also using only 64 bits. Again, excellent idea.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900