Re: Rounding of the double
- From: Joseph M. Newcomer <newcomer@xxxxxxxxxxxx>
- Date: Thu, 31 May 2007 14:01:21 -0400
That looks about right. You seem to be expecting that floating point is done in base 10,
which it is not. It is done in base 2, and results like this are what you should expect.
What you have to do is figure out how many decimal places you want, then add half of that,
e.g., if you expect 0.80, then you would add 0.005 to the result and display it to 2
decimal places. (The truth is vastly more complex and entire books have been written on
the subject)
The answer is that if you divide 80 by 100, you get 0.80, but there is no accurate
representation of 0.80 in IEEE floating point, so if you divide 80 by 100, you get the
closest approximation the representation can support, and when that representation is
converted to a textual representation you get 0.8000000004.
Essentially, fractions are represented by summing up powers-of-two fractional values to
the best approximation:
1/2 + 1/4 = 0.75
1/2 + 1/4 + 1/32 = 0.78125
1/2 + 1/4 + 1/32 + 1/64 = 0.796875
1/2 + 1/4 + 1/32 + 1/64 + 1/512 = 0.798828125
.... + 1/1024 = 0.7998046875
.... + 1/8192 = 0.7999267578125
.... + 1/16384 = 0.79998779296875
.... + 1/131072 = 0.79999542236328125
.... + 1/262144 = 0.799999237060546875
.... + 1/2097152 = 0.799999713897705078125
.... + left as an exercise for the student
The simplistic explanation is that the approximation that is used is the one that produces
the smallest error. (There are actually different rounding modes in IEEE floating point
and at that point you need to start somewhere like
http://en.wikipedia.org/wiki/IEEE_754 )
I was unable to find a round() function in the MSDN that applied to C/C++; I found
JScript, VBScript, and Crystal reports, but nothing for C/C++.
joe
On 31 May 2007 08:10:16 -0700, Alex <alsim123@xxxxxxxxxxx> wrote:
Everybody,Joseph M. Newcomer [MVP]
I'm lost
I have double d1 = 80.00
double d2 = 100.00
double result = d1/d2;
result = 0.80000000000000004 !!??
Why appears this "4" at the end!!??
It really makes difference for me.
And also if I use:
double dValue = atof( "0.80" );
if also returns 0.80000000000000004
Using of the round(...) function doesn't help
It returns 80.000000/100.0000000 which OF COURSE =
0.80000000000000004 !!!???
Is there any way actually if I divide 80 by 100 to get 0.80 ?
Thanks,
Alex
email: newcomer@xxxxxxxxxxxx
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
.
- Follow-Ups:
- Re: Rounding of the double
- From: Alex
- Re: Rounding of the double
- References:
- Rounding of the double
- From: Alex
- Rounding of the double
- Prev by Date: Re: Rounding of the double
- Next by Date: Re: Rounding of the double
- Previous by thread: Re: Rounding of the double
- Next by thread: Re: Rounding of the double
- Index(es):
Relevant Pages
|