0

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

1 Answer 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.