Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Incrimental loop is screwed up.

Status
Not open for further replies.

ArtSmart

Programmer
Sep 21, 2001
3
US
Somebody help a stupid guy and tell me why is it with microsoft 2 doesn't equal 2.

Here is a small example representing my problem:
Sub Test()
Dim SPD As Single
SPD = 0
SPDT:
SPD = SPD + 0.1
GoTo SPDT
End Sub

If you add a watch for SPD and a break point so you can actually monitor the change you will see that instead of getting to 0.8 SPD becomes 0.8000001 and after that everything is screwed up! Changing SPD type to double seems to help but it only seems like that. If you put a conditional watch, say BREAK WHEN SPD=5 it will never happen. Any ideas
 
Why are you using Goto??
Why aren't you using a proper loop??
 
This is just an example programm. The real programm is much more complex with a changing increment. And then, is method is perfectly legal and just as good as any other. I guess the question is why is it when you add 0.1 to o.7 it equals 0.800001?
 
Hi!

I can't tell you what's happening, though I have heard of this problem in Access (Someone explained it to me once and I think it had something to do with Binary addition, but that's all I remember). Try this code to break:

Break When Abs(5 - SPD) <= .000001

Of course you will need to choose a value that you are sure it will get less then, .0001 may be a better choice.

hth
Jeff Bridgham
 
Without 'explaination', jeff has the 'correect' approach.

the elplination is the simple look at the representation of 'values' in any computer/binary divice. Many (actually MOST) real values cannot be represented precisely, so you will always need to check them for a threshold value, boundary condition or Range. It is possible to calculate the possible 'error', depending on the &quot;TYPE&quot; of variable, however this is not commonly done.

Several variations on your specific test might include:


Sub Test()
Dim SPD As Single
SPD = 0
SPDT:
SPD = SPD + 0.1
If (Abs(5 - SPD) <= .000001) then
Exit Sub
End If

If (SPD <= 4.99999) then
Exit Sub
End If

If (SPD >= 5.000001) then
Exit Sub
End If

If (SPD <= 5.1 and SPD >= 4.9) then
Exit Sub
End If


GoTo SPDT
End Sub

MichaelRed
m.red@att.net

There is never time to do it right but there is always time to do it over
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top