On 02/06/12 09:52, Peter Otten wrote:

I just started programming so all this is new to me. I don't really
understand the explanation. I'm a novice at programming.

OK, Here is an attempt to explain the explanation!

Original question:
Why does -17 / 10  => -2 instead of -1

Python FAQ response:
> It’s primarily driven by the desire that i % j have the same
> sign as j.

The % operator returns the "remainder" in integer division.
It turns out that in programming we can often use the
remainder to perform programming "tricks", especially when
dealing with cyclic data - such as the days of the week.

For example if you want to find out which day of the
week it is 53 days  from now it is 53 % 7 plus whatever
todays number is... Now for those tricks to work we want
to have the % operator work as described in the FAQ above


> If you want that, and also want:
>
> i == (i // j) * j + (i % j)
>
> then integer division has to return the floor.

This is just saying that the integer division(//) result times the original divisor plus the remainder should equal the starting number.
Thus:

17/10 => 1,7
So (17 // 10) => 1 and (17 % 10) => 7
So 1 x 10 + 7 => 17.

And to achieve those two aims(remainder with the same sign as the divisor and the sum returning the original value) we must define integer division to return the "floor" of the division result.

The floor of a real number is the integer value *lower* than its real value. Thus:

floor(5.5) -> 5
floor(-5.5) -> -6

17/10 -> 1.7
floor(1.7) -> 1
-17/10 -> -1.7
floor(-1.7) -> -2

So X // Y == floor(X / Y)

HTH.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to