in reply to Weighted random numbers generator

Hi, I usually try to establish some kind of function (stepped or non-stepped) on probability. This can be quite an involved process if I'm, for instance, trying for a normal distribution. So (bear with my ideosyncrasies)-
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; } $y = rand(); # This bit constitutes the "function" $i = 0; until ($y < $x[$i]) { $i = $i + 1; } return $i;

Replies are listed 'Best First'.
Re: Re: Weighted random numbers generator
by Anonymous Monk on Mar 14, 2003 at 05:48 UTC
    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; }
      Bugger. Spot the derro who forgot to change @x to @_ in choose_weighted.