MathLib - computing modulo on real numbers in SystemVerilog

 Think of noise filtering algorithms, floating point computations etc. - a handy operator in such circumstances is modulo - loosely defined as a function that returns remainder after division (however, there is a close cousin rem - for later discussion).  System designers often use mod function to perform certain periodic functions, DSP algorithms etc. When such systems are implemented in hardware, designers often use Verilog to capture the same intent. Verilog (or SystemVerilog) has operator in-built to provide basic support for modulo computation - it works just fine for unsigned integers. However, in behavioral models, testbenches and AMS models, often real numbers get involved and suddenly you get an error from your favorite HDL simulator as below (Verilator as example):

%Error: t.sv:7:32: Expected integral (non-real) input to MODDIV
                 : ... In instance m
    7 |     $display ("3.2 MOD 1: %f", 3.2%1);
      |                                ^~~ 
For typical RTL designer, this may not be an issue, but for many others - like AMS engineers, verification engineers, architects et. al., this is a setback. Consider a simple Matlab code as below: 

mod_res = mod (-3.2, 2)
Matlab would print the result as 1.2 - sort of obvious, divide by 2, use real value computation and find the remainder, obvious isn't? 

Now, let's consider a model verified using Matlab with such coefficients including real numbers and it deploys mod in the core algorithm - how do we model that in SystemVerilog based verification environment? Look no further - use our time-tested MathLib as below:
 

  module m;

  import MathLib_pkg::*;

  real inp_real;
  real mod_result;
 
  initial begin : test
    inp_real = 3.2;
    mod_result = mod (inp_real, 2);

    $display ("inp: %f mod 2 result: %f", inp_real, mod_result);
  end : test
endmodule : m
So, what's the magic? Well, nothing much really - it is plain math behind 

mod(a,b)=ab·floor(ab)
 
Just that, MathLib does this under-the-hood and provides you handy API to use with scalar/vector/matrix inputs. 
MathLib is fun indeed!

Comments

Popular posts from this blog

Porting a complete UVC to Verilator + UVM - an anecdote!

Opensource testbench generator for VHDL designs, OSVVM included!

Don't go "wild" with Associative arrays in SystemVerilog - PySlint it!