Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Re: Weighted random numbers generator

by Anonymous Monk
on Mar 14, 2003 at 05:48 UTC ( [id://242960]=note: print w/replies, xml ) Need Help??


in reply to Re: Weighted random numbers generator
in thread Weighted random numbers generator

Woops! Should have placed greater focus on the word _establish_. To speed things up, I furnish the details of the function (in this case, $x$i within the "function" bit at the end), instead of re-evaluating it every time I call a subroutine. So, to clarify, say I use two subroutines, choose_weighted and weight_array.
my $etc = 0; my @x = (1.3, 1.4, 900, .03, 7, $etc, $etc); @x = weight_array(@x); my $random_value = choose_weighted(@x); sub weight array { my @x = @_; my $y = 0; my $i = 0; until ($i > $#x) { $y = $y + $x[$i]; $i = $i + 1; } $x[0] = $x[0] / $y; $i = 1; until ($i > $#x) { $x[$i] = $x[$i - 1] + $x[$i] / $y; $i = $i + 1; } return @x; } sub choose_weighted { my $y = rand(); my $i = 0; until ($y < $x[$i]) { $i = $i + 1; } return $i; }

Replies are listed 'Best First'.
Re: Re: Re: Weighted random numbers generator
by Anonymous Monk on Mar 14, 2003 at 05:51 UTC
    Bugger. Spot the derro who forgot to change @x to @_ in choose_weighted.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://242960]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-25 16:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found