I came across these statements in VHDL programming and could not understand the difference between the two operators mod and rem
9 mod 5
(-9) mod 5
9 mod (-5)
9 rem 5
(-9) rem 5
9 rem (-5)
I came across these statements in VHDL programming and could not understand the difference between the two operators mod and rem
9 mod 5
(-9) mod 5
9 mod (-5)
9 rem 5
(-9) rem 5
9 rem (-5)
A way to see the different is to run a quick simulation in a test bench, for example using a process like this:
process is
begin
report " 9 mod 5 = " & integer'image(9 mod 5);
report " 9 rem 5 = " & integer'image(9 rem 5);
report " 9 mod (-5) = " & integer'image(9 mod (-5));
report " 9 rem (-5) = " & integer'image(9 rem (-5));
report "(-9) mod 5 = " & integer'image((-9) mod 5);
report "(-9) rem 5 = " & integer'image((-9) rem 5);
report "(-9) mod (-5) = " & integer'image((-9) mod (-5));
report "(-9) rem (-5) = " & integer'image((-9) rem (-5));
wait;
end process;
It shows the result to be:
# ** Note: 9 mod 5 = 4
# ** Note: 9 rem 5 = 4
# ** Note: 9 mod (-5) = -1
# ** Note: 9 rem (-5) = 4
# ** Note: (-9) mod 5 = 1
# ** Note: (-9) rem 5 = -4
# ** Note: (-9) mod (-5) = -4
# ** Note: (-9) rem (-5) = -4
Wikipedia - Modulo operation has an elaborate description, including the rules:
n
in a mod n
a
in a rem n
The mod
operator gives the residue for a division that rounds down (floored division), so a = floor_div(a, n) * n + (a mod n)
. The advantage is that a mod n
is a repeated sawtooth graph when a
is increasing even through zero, which is important in some calculations.
The rem
operator gives the remainder for the regular integer division a / n
that rounds towards 0 (truncated division), so a = (a / n) * n + (a rem n)
.
For equal sign:
9/5=-9/-5=1.8 gets 1
9 mod 5 = 9 rem 5
-9 mod -5 = -9 rem -5
-----------------------------------------
For unequal signs:
9/-5 = -9/5 = -1.8
In "mod" operator : -1.8 gets -2
In "rem" operator : -1.8 gets -1
----------------------------------------
example1: (9,-5)
9 = (-5*-2)-1 then: (9 mod -5) = -1
9 = (-5*-1)+4 then: (9 rem -5) = +4
----------------------------------------
example2: (-9,5)
-9 = (5*-2)+1 then: (-9 mod 5) = +1
-9 = (5*-1)-4 then: (-9 rem 5) = -4
----------------------------------------
example3: (-9,-5)
-9 = (-5*1)-4 then: (-9 mod -5) = -4
-9 = (-5*1)-4 then: (-9 rem -5) = -4
----------------------------------------
example4: (9,5)
9 = (5*1)+4 then: (9 mod 5) = +4
9 = (5*1)+4 then: (9 rem 5) = +4
© 2022 - 2024 — McMap. All rights reserved.