I am writing the simplest loop on vba - passing X on the [a, b] segment, simultaneously calculating something. When X reaches b, the cycle stops. The simplest example is:

a = 3 b = 4 h = 0.1 x = a Cells(5, 1).Value = "x:" Cells(6, 1).Value = "y:" Do While x <= b ... тут всякие вычисления ... x = x + h Loop 

When passing through the Debugger, when x = 4, it is compared with b, which is also equal to 4, but it does not go into the body of the loop and goes, although there clearly stands x <= b .

What could be the snag?

  • Because In your case, x is of type Double , then b reduced to the same type. A comparison of floating-point numbers is a sore subject for most programming languages. Try in the comparison operator either to compare the difference with a certain value (error), or to round both numbers in the comparison operator to the desired accuracy. - Edward Izmalkov

1 answer 1

It is likely that the problem is that x is a floating point number after it has been added h . Accordingly, at each iteration of the cycle it will accumulate some error from addition with h .
In the end, it turns out that it is not 4 , but 4.0000000000001 (for example), which is greater than b .
Try

 epsilon = h/2 ... Do While x - epsilon <= b 
  • Yes exactly. Debugger showed that x = 4 , b = 4 and I completely forget about the error, thanks) - Denis