'Result of recursive function in Verilog

My math may not be serving me well. I've written a simple recursive function in Verilog to calculate value of log base 2. Log2(1000) should return 9.965 rounded to 10. But, my simulation shows that the function returns 9 as the final value of the recursive function. Any idea what I'm doing wrong?

module test;
  
real numBits;

function real log2 (input int X);
  if (X == 1)
        log2 = 0.0;
  else begin
        log2 = log2(X / 2) + 1.0;
        $display($stime,,,"log2 = %0d",log2);
  end
endfunction
  
initial begin
  numBits = log2(1000);
  $display($stime,,,"numBits = %f",numBits);
end

endmodule

Here's the EDA playground link that shows the code:

https://www.edaplayground.com/x/icx7



Solution 1:[1]

A couple of problems with your code. The first is the input to your function needs to be real. Then, it's never good to compare real numbers with equality do to rounding errors. Use X<=1 instead. And finally you should declare recursive functions with an automatic lifetime so that the arguments and the return values do not get overwritten.

function automatic real log2 (input real X);
  if (X <= 1)
      log2 = 0.0;
  else begin
    log2 = log2(X / 2) + 1.0;
    $display($stime,,,"log2 = %0g",log2);
   end
endfunction

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dave_59