Reference · Math

math.remainder

signature
math.remainder(num, num) -> float

What it does

The IEEE remainder: the first number minus the multiple of the second that is closest to it, as a float, as Python's math.remainder. The result lies between -|y| / 2 and |y| / 2, so it can be negative for positive arguments: math.remainder(8, 3) is -1.0, since 8 is closer to 9 than to 6. For the remainder with the dividend's sign use math.fmod or %.

Examples

print(math.remainder(7, 3), math.remainder(8, 3), math.remainder(7.5, 2))print(math.fmod(8, 3), 8 % 3)
output
1.0 -1.0 -0.52.0 2

Edge cases

print(math.remainder(7, 2), math.remainder(9, 2), math.remainder(-5.5, 1))print(math.remainder(7, float("inf")), math.remainder(-0.0, 3), math.remainder(float("nan"), 2))
output
-1.0 1.0 0.57.0 -0.0 NaN

Errors

A divisor of zero, or an infinite dividend, is a runtime error, math domain error, not an error value. An argument that is not a number is a runtime error as well.

this one fails
print(math.remainder(7, 0))
output
line 1: `math.remainder`: math domain error (7, 0)
this one fails
print(math.remainder(float("inf"), 3))
output
line 1: `math.remainder`: math domain error (inf, 3)

Chaining

In a pipeline the dividend comes first. The distance from the nearest multiple is its absolute value:

print(8 | math.remainder(3))print([7, 8, 9] | map((x) => math.remainder(x, 3)) | map(math.fabs))
output
-1.0[1.0, 1.0, 0.0]

See also

math.fmod, math.fabs, round

Thread
8Useful? Like it, or add to its thread below.

Thread 0 posts

On math.remainder(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo