math.remainder Rounds To The Nearest Multiple

math.remainder snaps to the nearest multiple so results land inside half the divisor, while % follows the divisor sign and fmod follows the dividend.

PythonData Integrity

Code

pythonsnippet
14 lines
import math

print("5 % 3:", 5 % 3)
print("fmod(5, 3):", math.fmod(5, 3))
print("remainder(5, 3):", math.remainder(5, 3))

# % follows the sign of the divisor, math.fmod follows the sign of the dividend
print("-5 % 3:", -5 % 3)
print("fmod(-5, 3):", math.fmod(-5, 3))
print("remainder(-5, 3):", math.remainder(-5, 3))

# remainder rounds to the nearest integer multiple: the result lands in [-y/2, y/2]
print("remainder(4, 3):", math.remainder(4, 3))
print("remainder(6, 3):", math.remainder(6, 3))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

5 % 3: 2
fmod(5, 3): 2.0
remainder(5, 3): -1.0
-5 % 3: 1
fmod(-5, 3): -2.0
remainder(-5, 3): 1.0
remainder(4, 3): 1.0
remainder(6, 3): 0.0

Putting it to use

Output lines are prefixed (5 % 3:, fmod(5, 3):, remainder(5, 3):), making each step’s effect easy to spot.

Output is labeled for readability — expect lines prefixed with 5 % 3:, fmod(5, 3):, remainder(5, 3):.

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `math`.