Re: quick question
From: John Carson (donaldquixote_at_datafast.net.au)
Date: 03/11/04
- Next message: Sharad Kala: "Re: quick question"
- Previous message: beav AT wn DoT com DoT au: "Re: quick question"
- In reply to: Snake: "quick question"
- Next in thread: Sharad Kala: "Re: quick question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 11 Mar 2004 15:38:33 +1100
"Snake" <hana1@rogers.com> wrote in message
news:fOR3c.250444$Qg7.127144@news04.bloor.is.net.cable.rogers.com
> Hello experts;
> I have a quick urgent question that I really need help with.
> if we have this simple program:
>
> void main(void){
>
> double x =( 5.6+3.1 +4.2 +1.8 +2.4);
> double y = 17.1;
> if(y == x){
> cout <<"equal"<<endl;
> }
> cout << (fabs(y-x))<<endl;
> cout <<x <<" "<< y;
> getch();
> }
>
>
> why equal does not appear on the screen?(in other words y!=x)
> and why their subtraction is not equal to zero?
> the thing that if you delete 2.4 from x and you make y = 14.7, they
> will be equal,strange?!!
> Any suggestion how I can output the subtraction as zero?!!
>
> Thank you guys very much
> Cheers!!
Floating point arithmetic is approximate. This is for a couple of reasons,
but the relevant reason in the present case is that floating point numbers
are stored internally as binary (base 2) numbers and not all decimal numbers
can be stored exactly as binary numbers. For example, while 5.6 is a
terminating decimal number, it is an infinitely repeating binary number.
Since only a finite number of digits is available for storing the number, it
follows that the binary version of the number is only approximate.
Sometimes binary number are exact and sometimes the errors cancel out, but
in general the result is only approximate. You have two choices:
1. Calculate the difference between two numbers and treat them as equal if
the absolute value of the difference is less than some small number.
2. Only work with integers.
-- John Carson 1. To reply to email address, remove donald 2. Don't reply to email address (post here instead)
- Next message: Sharad Kala: "Re: quick question"
- Previous message: beav AT wn DoT com DoT au: "Re: quick question"
- In reply to: Snake: "quick question"
- Next in thread: Sharad Kala: "Re: quick question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|