[Python-Dev] Floor division (original) (raw)

Tim Peters tim.peters at gmail.com
Fri Jan 26 00:11:23 CET 2007


[Guido]

The only thing I would miss about this is that I am used to write certain timing loops that like to sync on whole seconds, by taking time.time() % 1.0 which nicely gives me the milliseconds in the current second. E.g.

while True: dosomethingexpensiveonceasecondonthesecond() now = time.time() time.sleep(1.0 - (now % 1.0))

Indeed, the only use of floating % in the standard library I recall is the ancient

return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0

from the original Wichman-Hill random() generator. Maybe we could introduce "%" as a unary prefix operator, where %x means "the fractional part of x" ;-)

Are you opposed to importing math? The infix spelling had important speed benefits in random.py (random() was the time-critical function in that module), but the use above couldn't care less.

 time.sleep(1.0 - math.fmod(now, 1.0))

would do the same, except would be easier to reason about because it's trivially guaranteed that 0.0 <= math.fmod(x, 1.0) < 1.0 for any finite float x >= 0.0. The same may or may not be true of % (I would have to think about that, and craft a proof one way or the other -- if it is true, it would have to invoke something special about the modulus 1.0, as the inequality doesn't hold for % for some other modulus values).

Better, you could use the more obvious:

time.sleep(math.ceil(now) - now)

That "says" as directly as possible that you want the number of seconds needed to reach the next integer value (or 0, if now is already an integer).

I guess I could use (now - int(now)) in a pinch,

That would need to be

time.sleep(1.0 - (now - int(now)))

I'd use the ceil spelling myself, even today -- but I don't suffer "it's better if it's syntax or builtin" disease ;-)

assuming int() continues to truncate.

Has anyone suggested to change that? I'm not aware of any complaints or problems due to int() truncating. There have been requests to add new kinds of round-to-integer functions, but in addition to int().



More information about the Python-Dev mailing list