tags:

views:

2533

answers:

4

The python 2.6 docs state that x % y is defined as the remainder of x / y (http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex). I am not clear on what is really occurring though, as:

for i in range(2, 11):
    print 1.0 % i

prints "1.0" ten times, rather than "0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc).

+6  A: 

Modulo is performed in the integer context, not fractional (remainders are integers). Therefore:

1 % 1  = 0  (1 times 1 plus 0)
1 % 2  = 1  (2 times 0 plus 1)
1 % 3  = 1  (3 times 0 plus 1)

6 % 3 = 0  (3 times 2 plus 0)
7 % 3 = 1  (3 times 2 plus 1)
8 % 3 = 2  (3 times 2 plus 2)

etc

How do I get the actual remainder of x / y?

By that I presume you mean doing a regular floating point division?

for i in range(2, 11):
    print 1.0 / i
codelogic
The reminders are not necessarily integers, for example 2.5 % 2 = 0.5. It just happens to be that the correct answer to 1.0 % x is 1.0, for every x > 1.
sth
-1 because it's incorrect to say remainders are integers. In Python, `%` works on floating-point numbers and can give a non-integer result. (JavaScript too.)
Jason Orendorff
+3  A: 

Wouldn't dividing 1 by an number larger than it result in 0 with remainder 1?

The number theorists in the crowd may correct me, but I think modulus/remainder is defined only on integers.

Dana
1 divided by 4 results in 0 with a remainder of 0.25.
fatcat1111
Nooo...1.0 / 4.0 = 0.25. 1 / 4 = 0 remainer 1. I don't think mod does what you think it does.
Dana
Interpreted in the integer context, 1 % anything greater than it should give 1, so actually the OP's program is working perfectly, albeit not what he wants.
sykora
+4  A: 

I think you can get the result you want by doing something like this:

for i in range(2, 11):
    print 1.0*(1 % i) / i

This computes the (integer) remainder as explained by others. Then you divide by the denominator again, to produce the fractional part of the quotient.

Note that I multiply the result of the modulo operation by 1.0 to ensure that a floating point division operation is done (rather than integer division, which will result in 0).

Greg Hewgill
+2  A: 

You've confused division and modulus.

"0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc)."

That's the result of division.

Not modulus.

Modulus (%) is the remainder left over after integer division.

Your sample values are simple division, which is the / operator. Not the % operator.

S.Lott