There seems to be a bug with the "<" and ">" operators in combination with decimal numbers.
an example:
returns "5.1".
but "my variable" needs to be <5, so the highest value of "my variable" to run the condition = 4.9, and 4.9 + 0.1 = 5 and not 5.1.
Can anyone tell me what's the problem here?
Joren
(PS: I'm using scratch 1.2.1)
Last edited by JSO (2007-12-13 09:04:51)
Offline
Most computers can not represent decimal numbers exactly. They store a binary approximation internally and show you a rounded-off value in the display routines. So what is probably happening here is that on the last pass through the loop, the value is something like 4.9999997 so it passes the test, has 0.2 added to it, which is then rounded-off for display and you see it as 5.1. Decimal number comparison can be quite tricky, some programmers deal with this by programming in a small tolerance (much smaller than the step size but larger than the round-off error) to their comparisons to make sure they work. So they might compare My Variable to 5-0.001. This is not a perfect solution and maybe there are people in this forum who have a more elegant approach.
Offline
Yes, probably. Integers are usuaully much safer for comparisons, depending on how they are stored internally. I don't know how Scratch stores integers, whether it even differentiates between decimal numbers and integer numbers. Maybe one of the moderators will address this.
Offline
I'm not certain, but I believe that scratch just uses double-precision floating point for all numbers. Small integers will end up getting represented exactly (as will numbers like 1/2 and 3/4), but 1/10 is an infinitely repeating binary number, so can't be represented exactly in floating-point notation.
With floating point numbers, it is a a good idea never to use an equality test, but to use the > and < operators with a little extra "tolerance". Testing for x > 9.999 is fairly safe,
while testing for x = 10 is a bit risky.
Offline