Re: ISO help in probability



Helmut Giese wrote:
Hello out there,
I have a set of variables each of which has a certain weight or
probability assigned. Say
a -> 50
b -> 30
c -> 10
d -> 10
Hi Helmut,
This any better?:

#!/usr/bin/tclsh

set probabilities {a 50 b 30 c 10 d 10 }

set curr 0
foreach {tok prob} $probabilities {
        lappend ::stat(toks) $tok
        set ::stat($tok,min) $curr
        incr curr $prob
        set ::stat($tok,max) $curr

        set ::res($tok) 0
}
set ::stat(summ) $curr

# rand() gives an even distribution from 0.0 to 0.999999999
proc randtok {} {
        set rand [ expr { rand() * $::stat(summ) }]
        foreach tok $::stat(toks) {
                if { $rand >= $::stat($tok,min) } {
                        if { $rand < $::stat($tok,max) } {
                                return $tok
                        }
                }
        }
        return this_is_an_error
}

for {set i 0} {$i < 10000 } {incr i} {
        incr ::res([randtok])
}
parray ::res

#end

G!
uwe
.



Relevant Pages

  • Re: collect list
    ... set end $curr foreach tok $list { ... # puts stderr next:$tok set end $tok incr curr} default { ... lappend res $start - $end} else set curr $tok ...
    (comp.lang.tcl)
  • Re: collect list
    ... # puts stderr next:$tok set fmt {- $curr $tok} incr curr} default { ... eval lappend res $fmt set fmt {$tok} ...
    (comp.lang.tcl)
  • Re: final collect list, the sequel of all mothers
    ... # puts stderr duplicate:$tok ... lappend res $start - $end ... set curr $tok ...
    (comp.lang.tcl)
  • Re: collect list, now running in this cinema:
    ... # puts stderr next:$tok set fmt {- $curr $tok} incr curr} default { ... eval lappend res $fmt set fmt {$tok} ...
    (comp.lang.tcl)