http://www.perlmonks.org?node_id=1007460


in reply to Random generator fail

Do you want real numbers in the range (1 <= number < 99) on a windows system?

perl -e"print 1 + rand 98, qq(\n) for 1..100"
Bill

Replies are listed 'Best First'.
Re^2: Random generator fail
by Anonymous Monk on Dec 06, 2012 at 13:38 UTC

    Ok I have better understanding now, Bill your solutions works great!

    @MidLifeXis What is rational for rand to ignore $_. Appearently you pointing out that, solves my problem by using

    perl -wle "use 5.10.0; foreach (1..100) { say rand($_);};" 1.94992065429688 56.7288208007813 52.1597290039063 18.6995849609375 6.6961669921875 68.6776733398438 65.6177978515625 62.72314453125 52.1324157714844 ...

    But I think using additional line  { say rand($_); is completely un-neccessary. Thank you.

      Let's step through this:

      foreach (1..100) { say rand($_); }
      When $_ is equal to ...
      • ... 1, rand($_) cannot be larger than 1.
      • ... 2, rand($_) cannot be larger than 2.
      • ... 3, rand($_) cannot be larger than 3.
      • ... 4, rand($_) cannot be larger than 4.
      • ... 5, rand($_) cannot be larger than 5.
      • ... 6, rand($_) cannot be larger than 6.

      Look at one of my earlier posts on this thread. The documentation for rand states that 0 <= rand($x) < $x if $x > 0. To accomplish what you are trying to do would require that you do this:

      say 1 + rand(99 - 1) for (1..100)
      In my previous node, MAX = 99 and MIN = 1. The 1..100 is the number of iterations you wish to use. If you use rand($_), your results will be biased toward the lower end of the counter range.

      --MidLifeXis

        I agree with bias at lower end. Great, that is pretty much what I was looking for.

        Thank you

      My rand 98 generates random numbers in the range (0<= number < 98). Adding one to every random number changes the range to (1<=number<99). Using rand $_ would generate a very different sequence of numbers. In fact, the sample output that you show cannot be the first few numbers as your dots suggest. It is possible that they are the last few numbers.
      Bill

      forgot to add this:

      perl -wle "use 5.10.0; say int foreach (1..100) ;"

      Works as rand() should have.

        Works as rand() should have.
        Either your assumptions are wrong, or the documentation for rand does not match the implementation. Which do you think it is?

        --MidLifeXis

        This one is better

        perl -wle "use 5.10.0; say abs foreach (-5..5) ;" 5 4 3 2 1 0 1 2 3 4 5