Difference between mod and rem operators in VHDL?
Asked Answered
J

2

18

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)
Janeanjaneczka answered 15/9, 2014 at 13:9 Comment(1)
L
35

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:

  • mod has sign of divisor, thus n in a mod n
  • rem has sign of dividend, thus 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).

Laaland answered 15/9, 2014 at 14:15 Comment(0)
D
0
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
Doriadorian answered 24/11, 2017 at 6:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.