Difference between mod and rem operators in VHDL?

流过昼夜 提交于 2019-12-29 04:42:07

问题


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)

回答1:


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).




回答2:


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


来源:https://stackoverflow.com/questions/25848879/difference-between-mod-and-rem-operators-in-vhdl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!