Forum OpenACS Development: Malfunction of procedure randomRange

The actual implementation of randomRange procedure isn't right. The last value of the range "never" result.

Example:
randomRange 4

random result [0, 2.5) ----> randomRange return 0 (25%)
[0.25, 0.5) --> 1 (25%)
[0.5, 0.75) --> 2 (25%)
[0.75, 1) ----> 3 (25%)
[1] ----------> 4 (0.00001%)

The last value of the range [0, 4] has only one option and the rest has 100/range percentage aprox.

I solve this problem by doing the following:

ad_proc -public randomRange {range} {
Returns a pseudo-random number between 0 and range.
@return integer
} {
incr range
return [expr [expr {int([random] * $range)}] % $range]
}

Collapse
Posted by Luis Ig. Bacas on
How to reproduce:

set range 4

for {set i 0} {$i <= $range} {incr i} {
set a($i) 0
}

for {set i 0} {$i < 100000} {incr i} {
incr a([randomRange $range])
}

array get a

Resilt with randomRange:
0 24960
1 24994
2 25031
3 25015
4 0

Result with new proposal:
0 20024
1 19958
2 20032
3 20004
4 19982