negative numbers and integer division

Martin v. Löwis martin at v.loewis.de
Fri Oct 3 15:10:09 EDT 2003


"Matthew Wilson" <mwilson at sarcastic-horse.com> writes:

> Hi-
> 
> I just discovered this:
> 
> >>> -1 // 12
> -1
> >>> 1 // 12
> 0
> >>>
> 
> I thought that -1 // 12 would be 0 also.  

Why did you think that? Dividing -1 by 12 gives -1, with a remainder
of 11: -1*12 + 11 == -1.

> I'm writing a simple monthly date class and i need (-1,2001) to be
> translated to (11,2000).  Any ideas?

def norm_month(month, year):
    delta_year, month = divmod(month, 12)
    return month, year+delta_year

print norm_month(-1, 2001)

Regards,
Martin




More information about the Python-list mailing list