SystemVerilog: $random vs $urandom - IKSciting
1988
post-template-default,single,single-post,postid-1988,single-format-standard,bridge-core-2.8.7,qodef-qi--no-touch,qi-addons-for-elementor-1.7.1,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode-title-hidden,qode_grid_1300,footer_responsive_adv,qode-content-sidebar-responsive,qode-theme-ver-27.1,qode-theme-bridge,qode_header_in_grid,wpb-js-composer js-comp-ver-6.6.0,vc_responsive,elementor-default,elementor-kit-838

$random vs $urandom

SystemVerilog에서 random number generation을 위해 여러 가지 방법을 사용할 수 있다. 이번 post에서는 그 중 $random$urandom$urandom_range라는 system function에 대하여 간략히 설명하고 비교하고자 한다. 결론부터 이야기하자면 $random은 사용하지 않는 것이 좋다.

module top;
  
  int a;
  int unsigned b;
  bit [7:0] c;
  
  initial begin
    // not recommended
    a = $random();
    
    // recommended
    b = $urandom();
    c = $urandom_range(255, 0);
  end
  
endmodule: top

$random (not recommended)

  • 32-bit signed integer 값 반환
  • SystemVerilog LRM에서 $random에 대한 RNG 기술
  • 모든 thread의 $random은 동일한 RNG 사용

$urandom, $urandom_range (recommended)

  • 32-bit unsigned integer 값 또는 주어진 range 내의 값 반환
  • $urandom에 대한 RNG 구현 방식은 EDA vendor 별 상이
  • 각 thread 별 독립적인 RNG 사용

$random이 사용하는 RNG는 SystemVerilog LRM에 기술되어 있어 어떠한 simulator를 사용하든 (seed가 같다면) 항상 동일한 sequence의 random number를 생성한다. 얼핏 보면 이러한 특성으로 이해 $random이 좋다고 생각할 수 있지만, 실제로는 그렇지 않다. 모든 thread의 $random이 동일한 RNG를 사용하므로 $random call 순서가 조금이라도 변경되면 simulation 결과에 영향을 주기 때문이다.

반면 $urandom과 $urandom_range의 경우 thread 별로 독립적인 RNG를 갖기 때문에 random stability 측면에서 굉장히 유리한 장점을 갖는다. 따라서 $random 대신 $urandom$urandom_range를 사용하는 것이 좋다. Random stability에 대해 자세히 설명하고 있는 Random Stability 페이지를 참고하면 이해에 도움이 될 것이다.

References

2 Comments
  • Hieu Ho
    Posted at 01:17h, 17 September Reply

    Thank you for your post,
    In your first example, I tried and changed “int unsigned b;” to “int b;”
    When using $urandom, the result is still a SIGNED number.
    I tried on https://www.edaplayground.com
    Would you please explain this case ?
    Thank you very much.

    • IKS
      Posted at 01:18h, 17 September Reply

      Hi Hieu,

      SystemVerilog LRM (IEEE 1800-2017) says:
      “The system function $urandom provides a mechanism for generating pseudo-random numbers. The function returns a new 32-bit random number each time it is called. The number shall be unsigned.”

      So $urandom does return 32-bit unsigned random number.
      What you need to consider here is an implicit cast.

      The data types such as ‘int’ are signed by default.
      When you assign an unsigned number to ‘int’, it’s implicitly cast to signed number.

      Best regards,
      Jung Ik Moon

Post A Comment