09-26-2017, 00:11 +0200
Forum: Overview#tclcode snippets
Better randomish numbers depending on the underlying kernel
AuthorPost
elven  12-07-2005, 17:22   | Random numbers Jabber
security dept.
(Administrator)
Member since 03/2004
55 Posts
                                                                                                                              
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
if {![file exists "/dev/urandom"]} {
    error "This library needs to run on a urandom-enabled unixoid to work, such as Linux."
}

# Returns urandom data as a string.
# [++n++] bytes to read
# [++cast++] Cast arguments to a list of int
#
# Note: This *might* block on some systems, but
# really shouldn't.
proc urandom {{n 1} {cast 1}} {
    set n [expr int($n)]
    if {$n < 1 || $n > 65535} { set n 1 }
    set f [open /dev/urandom r]
    set b [read $f $n]
    close $f
    if {$cast == 1} {
        set x [list]
        foreach i [split $b ""] {
            scan $i "%c" n; lappend x $n
        };
        set b $x
    }
    return $b
}

# gives a completely random floating point number
# this is an evil hack, but works for now
proc urandf {} {
    while {1} {
        binary scan [urandom 4] f d
        if {[set d] != "nan"} { break }
    }
    return $d
}


irc.swordcoast.net
This post was edited 1 times, last on 08-14-2009, 03:19 by thommey
sKy\  12-13-2005, 17:50  
(Moderator)

Avatar

Member since 05/2005
8 Posts
Location: Germany, Zeitz
                                                                                                                              
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
# generate random integer number in the range [0,max]
proc RandomInteger1 { max } {
    return [expr {int(rand()*$max) + 1}]
}

# generate random integer number in the range [0,max-1]
proc RandomInteger2 { max } {
    return [expr {int(rand()*$max)}]
}

# generate random integer number in the range [0,max]
proc RandomInteger3 { max } {
    return [expr {int(rand()*($max+1))}]
}

# generate random integer number in the range [min,max]
proc RandomInteger4 { min max } {
    return [expr {int(rand()*($max-$min+1)+$min)}]
}


[Not loaded: http://sky.tclhelp.net/sky.gif]
This post was edited 1 times, last on 08-14-2009, 03:21 by thommey
Advanced options for this topic:

Ignore this topic (Do not list this topic in the "unread topics" search. You are currently not ignoring this topic.)
Hide this topic (Hidden topics are not displayed in the topics list. This topic is currently not hidden.)
Go to forum

Unclassified NewsBoard 1.5.3-d | © 2003-4 by Yves Goergen