0

I'm learning Python and I wish to know why "-40//60 = -1" and "-40 % 60 = 20"

My solution to this problem was turning the values to positive, but I don't get why it is returning these values.

import math

class Clock:
    def __init__(self, hour, minute):
        self.hour = hour
        self.minute = minute
        self.extra_hour = 0
        if self.minute >= 60:
            self.hour += (self.minute // 60)
            self.minute = (self.minute % 60)
        while self.hour >= 24:
            self.hour -= 24
        if self.minute < 0:
            self.hour -= int((math.sqrt(self.minute**2)//60) + 1)
            self.minute = int(60 - (math.sqrt(self.minute**2) % 60))
        while self.hour < 0:
            self.hour += 24
kruffer
  • 3
  • 2
  • 1
    Python rounds down. You are expecting round-towards-zero. However, "-40 % 60" should equal 20. That's the proper answer. – Tim Roberts Nov 11 '21 at 18:29
  • 1
    `//` is explicitly *floor* division, not *truncating* division. – ShadowRanger Nov 11 '21 at 18:32
  • One important thing to note is that unary minus has a higher precedence than % or //. So -40//60 is parsed as (-40)//60, not -(40//60). Likewise -40%60 is (-40)%60, not -(40%60). – Stef Nov 11 '21 at 18:36
  • To see why you _want_ this behavior (rounding towards negative infinity): For a given pair of integers `p` and `q`, the integers `p//q` = n, and `p%q` = r satisfy `p = n * q + r`. By rounding down for `p//q`, you satisfy this and always have `0 ≤ r < q`. – tegancp Nov 11 '21 at 18:43
  • All that being said, this behaviour of // and % with negative numbers appears to make things more simple, not more complicated, for your Clock class. Consider: `class Clock: def __init__(self, h, m): self.hour = (h + m//60) % 24; self.minute = m % 60; def __repr__(self): return '{}:{}'.format(self.hour, self.minute)`. Then for instance, `Clock(0, -40)` is printed as `'23:20'`, which I think is what you want? – Stef Nov 11 '21 at 18:43
  • Thank you so much, really helpful! – kruffer Nov 11 '21 at 19:57

0 Answers0