Python Forum

Full Version: math.remainder(a, b) question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import math
print(math.remainder(7, 2))
Output:
-1.0
Shouldn't the output be 1.0? Think

Then ...

import math
print(math.remainder(33, 2))
Output:
1.0
Then I tried ...
import math
print(math.remainder(5, 2)
Output:
1.0
What I could gather is that if the dividend (the number which is divided) is a power of 2 plus 1 (2n + 1), we get a remainder 1, but if it isn't we get a remainder of -1.0.

What's going on? Huh
Read the docs

https://docs.python.org/3/library/math.html

Quote:math.remainder(x, y)ΒΆ
Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder(x, y) thus always satisfies abs® <= 0.5 * abs(y).

According to that, remainder(3, 2) == -1. also 11, 15 or any 2*n - 1 where n is even. Half the time.

You could use the modulo operator (%)

https://docs.python.org/3.3/reference/expressions.html

Quote:The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [1].
print(7 % 2, math.remainder(7, 2))
Output:
1 -1.0