r...@goto10.org wrote:
> hi,
> 
> i am finding something couter intuative about randomness and search for a 
> solution.
> 
> i have a bit of code that randomly selects a number from an array and then 
> adds 
> it to the previous number.  I have two positive numbers and their negitives  
> qw(1 2 -1 -2)
> 
> i expected the below code to hover around 0 up and down a bit in each 
> direction 
> - but it very quickly shoots of into big numbers.
> 
> i would like to have a way to contain the output range to  between -45 and 45 
> for example.
> 
> anyone have a clue how to do this?
> 
> thanks
> 
> rob
> 
> #!/usr/bin/perl
> use strict;
> use warnings;
> 
> my @intervalset = qw(1 2 -1 -2);
> 
> my $current = 0;
> 
> my $t = 1;
> 
> while ($t==1){
> 
> my $rndi  = $intervalset[rand @intervalset];
> 
> $current = ($rndi+$current);
> 
> print $current,"\n";
> 
> }

You are falling for the fabled 'law of averages' that tells people they are more
likely to win the lottery after losing many times. The sum will not hover around
its starting value as each random number is independent. If your total has
reached, say, 100 then you are still no more likely to roll negative numbers
than positive ones.

The expected, or mean value of the rolls is zero, but the variance of the total
increases with the number of rolls and so you will see it stray further and
further from zero as your program continues.

Please explain what numbers you are trying to generate. If you want an even
distribution of integers from -45 to 45 then simply use

  my $num = int(rand 91) - 45, "\n";

Also, please indent your code inside a block to make it more legible. And the
usual way of writing an indefinite loop is

  while (1) {
    :
  }

HTH,

Rob

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to