Re: Singles to Doubles
- From: "Jim Mack" <jmack@xxxxxxxxxxxxxxx>
- Date: Mon, 16 Jul 2007 16:45:44 -0400
Karl E. Peterson wrote:
Hi Bob --
What the heck? Seems silly to have to convert it to a String
first, then to a Double. But, it is more accurate. Anyone know of
a less ugly way to accurately replicate a Single with a Double, or
this the best it gets?
Isn't it mainly that the Single isn't representing the value as
accurately?
I guess, yeah. But how is it that a *String* seems to do so even
more accurately?
For discussion purposes, I modified your example just a bit:
Public Sub Main()
Dim s As Single
Dim d1 As Double
Dim d2 As Double
s = 0.3026!
d1 = s
d2 = CDbl(CStr(s))
Debug.Print s, d1, d2
Debug.Print s = d1, s = d2
Debug.Print s - d1, s - d2
End Sub
Which gives me these results:
0.3026 0.302599996328354 0.3026
True True
0 -3.67164609826887E-09
And, of course, the value I'm after *is* 0.3026 -- not the one that's
off
0.00000000367... Seems like some sort of register garbage that I'm
picking up in
the conversion?
Thanks... Karl
The best representation of a value as a single can use all 24 bits of mantissa, and still not be exact. The double representation gets a lot closer, using 53 bits of mantissa. But there's no way to guess what those new bits are supposed to be.
During a conversion from single to double, all the extra bits of mantissa are (must be) set to 0. That makes for a significantly different representation than the best one for your value. Notice that the error term is down in the range of 10^-8, which is close to 2^-24, where the break to all zeros occurs.
In the string domain the value is exact, and can be converted to a double using all 53 bits of precision.
So yes, you get the best result if you pass through a domain where the value is exact. In this case you could also have transitioned through a Currency value and gotten the same good results.
--
Jim Mack
MicroDexterity Inc
www.microdexterity.com
.
- Follow-Ups:
- Re: Singles to Doubles
- From: Michael C
- Re: Singles to Doubles
- From: Karl E. Peterson
- Re: Singles to Doubles
- References:
- Singles to Doubles
- From: Karl E. Peterson
- Re: Singles to Doubles
- From: Bob Butler
- Re: Singles to Doubles
- From: Karl E. Peterson
- Singles to Doubles
- Prev by Date: Re: Singles to Doubles
- Next by Date: Re: Singles to Doubles
- Previous by thread: Re: Singles to Doubles
- Next by thread: Re: Singles to Doubles
- Index(es):
Relevant Pages
|