Single/Double type mixing: Is this unbelievable VB bug or what?
Posted on 2014-11-14
I have found that the following example code, produces very unexpected result
Private Sub Command1_Click()
Dim Sng As Single
Dim Dbl As Double
Sng = 1.1
Dbl = sng
The result was 1.10000002384186
Now, I’m of course aware of floating point data tape limitations, and that when working with, for instance double precision variables, some fluctuating error at the 1.100000000000xy positions might be expected, since the floating types in general case can only be approximately represented.
However, this behavior in example is unexpected and strange to me. Why would assigning a Single value do a Double introduce such enormous error? This can have particularly dire consequences, as in a case that happened to me: you work extensively with Doubles, in order to increase the precision of calculations, and then, at only one place, you use a Single for a variable, and multiplies a Double, and ruin all pression calculation you’ve done so far!
I’ve checked, and this happens in Vb6, VB.Net, QuickBasic. I suspect, this might be just the way processors handles Singles/Doubles, in visual basic or other languages?
Why? Why in the previous example, the result for Dbl is not simply 1.1 or at least 1.100000000000xy
It seems as if processor/compiler/whatever for 8 bytes of Dbl, assigns for first 4 bytes the 4 bytes from single, and gets 1.1000000, and then for the rests, it uses the values it found in memory in the following 4 bytes…