negative numbers and integer division


M

Matthew Wilson

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?
 
Ad

Advertisements

M

Martin v. =?iso-8859-15?q?L=F6wis?=

Matthew Wilson said:
Hi-

I just discovered this:


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
 
M

Mark Hahn

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).
 
S

Skip Montanaro

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
 
R

Rainer Deyke

Matthew said:
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?

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)
 
Ad

Advertisements

P

Peter Abel

Matthew Wilson said:
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?

Maybe the following could help:.... return (((month+11) % 12)+1,year+((month-1)/12))
....
Regards
Peter
 
Ad

Advertisements

M

mensanator

Matthew Wilson said:
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?
11
 

Top