differance between float and doble

Jun 17, 2015 at 10:22am
#include<iostream>
#include<conio.h>
using namespace std;


void main()
{
float a=0.15;
double b=0.15;


if(a==b)
cout<<"equals";
else cout<<"not equals";

}






in above code when i assing values to variable a & b in multiple of 0.25 ie .25,.5,.75,1.25 etc. then output is equals and all other conditions output is not equals



i not get why it is plz help me.
Jun 17, 2015 at 10:28am
welcome to floating point precision pain:
https://blogs.office.com/2008/04/10/understanding-floating-point-precision-aka-why-does-excel-give-me-seemingly-wrong-answers/

in other words testing for equality of floats or doubles:
if(a==b)
is something you should NEVER do.
Jun 17, 2015 at 10:52am
And short explanation on how floating point numbers are stored ad what the difference between single and double precision:
https://en.wikipedia.org/wiki/IEEE_floating_point
Jun 17, 2015 at 12:42pm
when i assing values to variable a & b in multiple of 0.25 ie .25,.5,.75,1.25 etc. then output is equals and all other conditions output is not equals

mutexe and MiiNiPaa have already pointed you at more detailed explanations.

But in a nutshell, .25, .5, .75, 1.25, ... work when other values don't as they are expressible as the sum of values which are all powers of 2.

As computers store numbers as binary, the only thing they can represent accurately (to the limit of their precision) are numbers that are a sum of powers of two.

0.25 = 2-2 (or (1/2)2)
1.25 = 20 + 2-2
...

And

1.33203125 = 20 + 2-2 + 2-4 + 2-6 + 2-8

Andy
Last edited on Jun 17, 2015 at 1:01pm
Jun 17, 2015 at 12:58pm
To better understand how that can limit precision, try to write 1/3 or 1/27 in decimals.
In base 3 it would be 0.1 or 0.001 respectively. In base 10... it is infinite number taking infinite amount of pages to write. As there is no such thing as infinite pages (or memory) we need to limit ourselves, say to 4 decimal places max, so 1/3 will be written as 0.3333. And when we multiply it again, we get 0.9999 : not the original value!

float and double has different precision: it is the equivalent of writing result with, say 2 and 4 decimal places:
1/16 = 0.06
1/16 = 0.0625
When we compare them this happens: 0.06 == 0.0625 — obviously false.
Topic archived. No new replies allowed.