Forum Discussion
How random is rand()?
Hi Rob,
Here is a method we used for a customer to generate a unique ID per HTTP request:
when RULE_INIT {
Initialize 10 variables to track the distribution of first digits
for {set i 0} {$i < 10} {incr i} {
set $i 0
}
Loop through and generate X number of random numbers
for {set i 0} {$i < 1000} {incr i} {
Save a new random number
set random_number [expr {rand()}]
set random_number_float [format %0.10f $random_number]
Log the random number, the formatted string and the first digit
log local0. "$random_number, [format %010s [string range $random_number 2 12]],\
[string range [format %010s [string range $random_number 2 12]] 0 0], $random_number_float"
incr [string range [format %010.f [string range $random_number_float 2 12]] end end]
}
log local0. "Summary: "
for {set i 0} {$i < 10} {incr i} {
log local0. "$i: [set $i]"
}
}
For a run of 100,000 iterations, the distribution is fairly even:
Rule : Summary:
Rule : 0: 10114
Rule : 1: 9981
Rule : 2: 9781
Rule : 3: 9980
Rule : 4: 10104
Rule : 5: 9993
Rule : 6: 10074
Rule : 7: 10067
Rule : 8: 10013
Rule : 9: 9893
I got the basics from this TCL wiki page (http://wiki.tcl.tk/17696). I didn't seed rand as there were a few people stating:
as specifying our own seed for every call to roll is more likely to reduce randomness than improve it, I've left it out altogether.
Aaron
Help guide the future of your DevCentral Community!
What tools do you use to collaborate? (1min - anonymous)Recent Discussions
Related Content
* Getting Started on DevCentral
* Community Guidelines
* Community Terms of Use / EULA
* Community Ranking Explained
* Community Resources
* Contact the DevCentral Team
* Update MFA on account.f5.com
