Search code examples
floating-pointverilogdivisionsystem-veriloginteger-division

Floating Point Division in System Verilog


I wanted to use floating point numbers in System Verilog using the real data type. I tried the following code, but it doesn't seem to work. I'm getting 2.000000 where I expect 2.500000.

Module:

module real_check(input [31:0]a, [31:0]b,
                  output real c);
    assign c = a/b;
endmodule

Test bench:

module tb_real_check();

real c;
reg[31:0] a, b;
real_check dut(a, b, c);

initial 
begin

  a <= 5;
  b <= 2;
  #50;
  $display("Answer : %f ", c);

end
endmodule

Solution

  • You are doing integer division. When calculating int/int (reg[31:0]/reg[31:0]), the result is an integer. So, when you calculate 5/2, you get 2.5 truncated to 2 which is then converted into a floating point (real) number as 2.000.... If you want floating point division (which doesn't discard the decimal), you need to have your operands (dividend & divisor) be floating point.

    So, to fix your code, your module needs to take two floating point numbers as input:

    module real_check(input real a, real b,
                      output real c);
    

    And in your test case, you need to declare a and b as floating point numbers:

    real a, b;