473,324 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

double compare 0.2 != 0.2 How?

344 100+
I'm working on a real-time reservation graph. And it keeps giving me error even I tested each Method and each statement except this one, which I did this early morning.
What suppose these statements do?
Expand|Select|Wrap|Line Numbers
  1. MessageBox.Show(Convert.ToString((1.0 - 0.8) == 0.2));
I felt wrong about anything I didn't see, I tested this too
Expand|Select|Wrap|Line Numbers
  1. MessageBox.Show(Convert.ToString(((double)(1.0 - 0.8)).CompareTo(0.2)));
I waited for True from each, but both give false!!!

Help!!!!!!!!!!!!!
Please any help!!!!!!!!!
Apr 26 '09 #1
18 8998
artov
40
Because 0.2 cannot be represented exact on floating point, value readed by the compiler and calculated from two double numbers (where 0.8 cannot also be repsesented exact), there has to be some differences.

For online help, check http://www.h-schmidt.net/FloatApplet/IEEE754.html or read wikipedia.
Apr 27 '09 #2
Plater
7,872 Expert 4TB
What error are you getting?
EDIT: NM I see
Apr 27 '09 #3
Bassem
344 100+
Great I know the representation of a floating-point number. But What should I do?!
I'm comparing two double numbers and get wrong result.
Any idea. I can't step back for that, my application depends on that comparison.
Apr 27 '09 #4
Plater
7,872 Expert 4TB
Outside the box time.

Consider this:
Expand|Select|Wrap|Line Numbers
  1. double a = 1.0;
  2. double b = 0.8;
  3. double c = 0.2;
  4. MessageBox.Show("" + ((a - b) + (a - c) == a));
  5.  
The result is true. Perhaps you can work out the routine to do this to fit your needs?
Apr 27 '09 #5
Bassem
344 100+
Hello Plater,
I'm so sorry for wasting your time with such a question. Thanks for replying.
I tested your code and the result is True, as it should of course.
Could you please test mine, it also should give True, but I swear with VS2005 that it gives me False.
Expand|Select|Wrap|Line Numbers
  1.             double a = 1.0;
  2.             double b = 0.2;
  3.             double c = 0.8;
  4.  
  5.             MessageBox.Show("" + ((1.0 - 0.8) == 0.2));
I fell stupid to ask you this, please copy and test it.
Tell me why it gives False!
Again I've to say sorry for wasting your time.

Regards,
Bassem
Apr 28 '09 #6
Plater
7,872 Expert 4TB
No no, you are correct, yours will give false.
I speculate that since one side is a specified value and the other is computed they are treated differently.
That is why I was saying use my code, they are functionaly identical mathmatically.

If yours was a function like this:
Expand|Select|Wrap|Line Numbers
  1. bool TestDouble(double a, double b, double c)
  2. {
  3.     return ((a - b) == c); 
  4.     //could also write it ((2*a - b - c)==a)
  5. }
  6.  
You would call it with:
MessageBox.Show(TestDouble(1.0,0.8,0.2).ToString() );

But as you said, you will get "False" instead of the expected "True"

So if you instead used my function:
Expand|Select|Wrap|Line Numbers
  1. bool TestDouble(double a, double b, double c)
  2. {
  3.     return ((a - b) + (a - c) == a)); 
  4. }
  5.  
You could again call it with:
MessageBox.Show(TestDouble(1.0,0.8,0.2).ToString() );

Only now you would get the expected "True"
Apr 28 '09 #7
Bassem
344 100+
This is the most strange thing I ever seen in C#, Can you please give me a reference to read more. I didn't understand yet the difference.
Apr 28 '09 #8
Curtis Rutland
3,256 Expert 2GB
This is an interesting topic. I'm just commenting to subscribe and remind me to look at it later.
Apr 28 '09 #9
Sorry I didn't reply earlier. Account has been locked out and only just figured out how to create a new account with my existing email address.

Anyway, what you need to look at is Math.Round(). I believe if you do the following you'll get your answer.

Expand|Select|Wrap|Line Numbers
  1. MessageBox.Show(Math.Round(1.0 - 0.8, 1) == 0.2));
Apr 29 '09 #10
Curtis Rutland
3,256 Expert 2GB
I'm actually interested in the "why" of this problem. Why does a computed value differ from a literal in this case.
Apr 29 '09 #11
@insertAlias
Quite simply because it is floating point arithmetic. It's a well known common problem.

http://en.wikipedia.org/wiki/Floating_point
Apr 29 '09 #12
r035198x
13,262 8TB
The morale of the story is that never (ever) use == (or !=) for comparing floating point numbers. There are numbers that the computer cannot represent in binary exactly simply because they are recurring numbers. For those numbers, the exact value stored is dependent on the platform being used and the precision possible on those platforms.
e.g
(Requesting your forgiveness for polluting your esteemed forum with the dreadful Java codes)
Expand|Select|Wrap|Line Numbers
  1. System.out.println(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1);
does not print 1.0 on my computer.

Here is What every computer scientist should know about floating point arithmetic
Apr 29 '09 #13
I'm kinda amazed that the other moderator/forum leaders didn't know this actually... You can't get very far with doubles without knowing about the rounding issues.
Apr 29 '09 #14
r035198x
13,262 8TB
I'm not too amazed. The forum administrative roles do not reflect on how much someone knows about subjects. They do know some pretty amazing things though which I don't know too. That's what makes forums amazing. Everyone gets to learn.
Apr 29 '09 #15
Curtis Rutland
3,256 Expert 2GB
Most of my work thus far hasn't had much to do with floating point precision, I'm sure I would have found some of that info if I was ever required to.
Apr 29 '09 #16
vekipeki
229 Expert 100+
That is how things work, the only thing you can do is add a handy extension method to System.Double, something like:

Expand|Select|Wrap|Line Numbers
  1. public static bool AlmostEquals
  2.      (this double a, double b)
  3. {
  4.     return (Math.Abs(a - b) < 1e-5);
  5. }
and then use it, when appropriate, like
Expand|Select|Wrap|Line Numbers
  1. MessageBox.Show((1.0 - 0.8).AlmostEquals(0.2));
Although if this is only a unit test, you might just add a method to your test module.
Apr 30 '09 #17
@vekipeki
Not sure off the top of my head, but is it possible to overload the double == operator in a similar approach using extension methods?
Apr 30 '09 #18
vekipeki
229 Expert 100+
No, you cannot override the existing == operator (it is a static method). But I wouldn't call that a good idea even if it were possible, modifications like that would be a nightmare to debug.
Apr 30 '09 #19

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Megan | last post by:
Hi everybody- I'm helping a friend with a music database. She has an old one and is creating a new one. She wants to compare records and fields in the old database with records and fields in the...
4
by: Jonathan Fielder | last post by:
Hi, My program (below) casts a double (which is in range for a float) to a float. As far as I know this should give me the nearest representable float, which will loose some precision. I...
4
by: MFRASER | last post by:
How can I compare two double values and return the greater of the two values? example double doublea = 1.0; double doubleb = 2.0 double retVal = ?compare doublea and doubleb
0
by: Frank King | last post by:
Hi, I am using CArray and quick sort funciton to sort an array of double type of data points. I found an article in MSDN HOWTO: Quick Sorting Using MFC CArray-Derived Classes ID: Q216858 ...
3
by: Andrew Murray | last post by:
Is it possible to compare a double with a float in c# without casting to one of the types first? It appears you cannot... float num = 1.545f; double dnum = 1.545; if (dnum == num)
3
by: Benny Ng | last post by:
Dear all, The following is the source. The password is encrypted and saved into the Binary in SQL2K. Now I want to create a new page to compare the existed password and the password that in the...
29
by: Virtual_X | last post by:
As in IEEE754 double consist of sign bit 11 bits for exponent 52 bits for fraction i write this code to print double parts as it explained in ieee754 i want to know if the code contain any...
26
by: neha_chhatre | last post by:
can anybody tell me how to compare two float values say for example t and check are two variables declared float how to compare t and check please help me as soon as possible
1
by: rockchicx23 | last post by:
i have to develop this snack machine program that makes you chose a snack put money in and give change here is my code so far, what do i use so the program compare the price and money deposited, I...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.