02 Nov $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
- https://www.systemverilog.io/randomization
- https://stackoverflow.com/questions/36698091/urandom-range-urandom-random-in-verilog/36711593#36711593
Jung Ik Moon
Verification Engineer
Hieu Ho
Posted at 01:17h, 17 SeptemberThank 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 SeptemberHi 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