Re: ifstream bug in VS2005 Beta2 & Platform SDK
- From: "Stephen Howe" <stephenPOINThoweATtns-globalPOINTcom>
- Date: Thu, 2 Jun 2005 13:52:34 +0100
> But if someone wrote some number into some media, this
> would be reasonable to expect this data to be read exacly as it was
written.
It is not reasonable and cannot be done.
You know the number 1/3?
Written in decimal it is 0.33333333333333333... forever.
It is said to "recur".
No matter how many places you chop the number of digits off at, it will
never represent 1/3.
And it works out that in any base, only fractions that are multiple of the
divisors of the base are exact.
So mulitples of 1/5 and 1/2 are exact in base 10 because 5 and 2 divide into
10 exactly.
And also powers and combinations. So 3/25 and 7/40 are exact.
Coming back to float's and double's:
Just about all languages use IEEE as the representation.
And that is binary format - so base 2
And that means in base 2 only fractions that are multiples and powers of 1/2
are exact.
So 1/10 or 0.1 is not, it recurs, and cannot be represented exactly as a
float or double.
What you have is a binary approximation, the closest binary approximation to
1/10.
And when you write a float or double to cout, you are converting from a base
2 representation that is exact to a base 10 textual representation. In this
conversion, with unlimited precision, it is always exact because 2 divides
into 10. But converting the other way is inexact. Not all base 10 numbers
have a base 2 representation because of the chopping-when-recurring problem.
Stephen Howe
.
- Follow-Ups:
- Re: ifstream bug in VS2005 Beta2 & Platform SDK
- From: Pete Becker
- Re: ifstream bug in VS2005 Beta2 & Platform SDK
- References:
- ifstream bug in VS2005 Beta2 & Platform SDK
- From: Sergei Nikolaev
- Re: ifstream bug in VS2005 Beta2 & Platform SDK
- From: Carl Daniel [VC++ MVP]
- Re: ifstream bug in VS2005 Beta2 & Platform SDK
- From: Sergei Nikolaev
- ifstream bug in VS2005 Beta2 & Platform SDK
- Prev by Date: allocator question (reposted here... sorry for the mistake)
- Next by Date: Re: ifstream bug in VS2005 Beta2 & Platform SDK
- Previous by thread: Re: ifstream bug in VS2005 Beta2 & Platform SDK
- Next by thread: Re: ifstream bug in VS2005 Beta2 & Platform SDK
- Index(es):
Relevant Pages
|