negative numbers and integer division

Discussion in 'Python' started by Matthew Wilson, Oct 3, 2003.

  1. Hi-

    I just discovered this:

    I thought that -1 // 12 would be 0 also. I'm writing a simple monthly
    date class and i need (-1,2001) to be translated to (11,2000). Any ideas?
     
    Matthew Wilson, Oct 3, 2003
    #1
    1. Advertisements

  2. Why did you think that? Dividing -1 by 12 gives -1, with a remainder
    of 11: -1*12 + 11 == -1.
    def norm_month(month, year):
    delta_year, month = divmod(month, 12)
    return month, year+delta_year

    print norm_month(-1, 2001)

    Regards,
    Martin
     
    Martin v. =?iso-8859-15?q?L=F6wis?=, Oct 3, 2003
    #2
    1. Advertisements

  3. Matthew Wilson

    Mark Hahn Guest

    That definitely seems wrong to me, even though it is a correct "floor"
    function.

    I was given the impression that (int // int) was going to be the replacement
    for (int / int) when (int / int) is changed to return a float, but -1/12 now
    gives 0, not -1, so (int // int) is not a replacement for (int / int).
     
    Mark Hahn, Oct 3, 2003
    #3
  4. Matthew Wilson

    Mark Hahn Guest

    oops -- ignore that last post -- i was totally wrong
     
    Mark Hahn, Oct 3, 2003
    #4
  5. Mark> I was given the impression that (int // int) was going to be the
    Mark> replacement for (int / int) when (int / int) is changed to return
    Mark> a float, but -1/12 now gives 0, not -1, so (int // int) is not a
    Mark> replacement for (int / int).
    -1

    Skip
     
    Skip Montanaro, Oct 3, 2003
    #5
  6. Matthew Wilson

    Rainer Deyke Guest

    Luckily for you, Python integer division does the right thing. You
    *want* -1 // 12 to be -1 for your application.

    def normalize_date(month, year):
    return (month % 12, year + month // 12)

    normalize_date(-1, 2001) # Returns (11, 2000)


    'normalize_date' as given assumes 'month' is in the range from 0 to 11; use
    this if your months are in the range from 1 to 12:

    def normalize_date(month, year):
    return ((month - 1) % 12 + 1, year + (month - 1) // 12)
     
    Rainer Deyke, Oct 3, 2003
    #6
  7. Matthew Wilson

    Peter Abel Guest

    Maybe the following could help:.... return (((month+11) % 12)+1,year+((month-1)/12))
    ....
    Regards
    Peter
     
    Peter Abel, Oct 3, 2003
    #7
  8. Matthew Wilson

    mensanator Guest

    11
     
    mensanator, Oct 3, 2003
    #8
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.