This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Zoinky's profile picture

Weird 'if' output?

Started by Zoinky, 23 November 2012 - 05:17 PM
Zoinky #1
Posted 23 November 2012 - 06:17 PM
Hey, I was messing around with the 'os.time()' and 'os.clock()' features of the os API and I stumbled along something odd.

clock = os.clock()
time = os.time()

sleep(1)

clock = os.clock() - clock
time = os.time() - time

print("Clock: "..clock)
print("Time: "..time)

if time ~= clock/50 then
  print("Time was changed")
end
The code above will print "Time was changed" even though time was actually clock/50. Am I using the wrong operator or is my math just fail? Anyway, I was just wondering if someone could answer that for me. Since I'm a little stumped.
Grim Reaper #2
Posted 23 November 2012 - 06:58 PM
If you're trying to check whether or not those values are the same, then yes, you're using the wrong operator.
The operator you're currently using is the 'not equal to' operator.

~=

If you're trying to check whether or not their equal, then you'd want to use the following comparison operator:

==
Zoinky #3
Posted 23 November 2012 - 11:22 PM
If you're trying to check whether or not those values are the same, then yes, you're using the wrong operator.
The operator you're currently using is the 'not equal to' operator.

~=

If you're trying to check whether or not their equal, then you'd want to use the following comparison operator:

==
I don't think I'm using the wrong operator. Although, I am not the most experienced coder. Anyone got any other ideas?
ChunLing #4
Posted 24 November 2012 - 03:16 AM
First, time and clock are both floating point numbers. They are rarely going to end up giving equality (particularly when you divide one of them by a number that doesn't factorize down to twos). Second, os.clock and os.time aren't scaled the same, one is in seconds and the other is in hours.

But the first hurdle is the big one, floating point numbers look equal to the significant digits a lot more often then they actually are equal in the eyes of a computer.